var s1 = "foo|bar|test";
var n1 = s1.split('|');
console.log(n1.pop())
var pip = s1.lastIndexOf('|');
console.log(s1.substring(pip + 1));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.split | |
Substring |
Test name | Executions per second |
---|---|
Array.split | 57015.2 Ops/sec |
Substring | 69869.9 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is testing two different approaches to perform a string manipulation operation:
split()
method to split a string into an array of substrings separated by a specified delimiter ('|'
).substring()
method to extract a part of a string starting from a specified index (lastIndexOf('|')
).Options Compared
The benchmark is comparing two options:
split()
: This option uses the split()
method to split the string into an array, and then accesses the last element using pop()
.substring()
: This option uses the lastIndexOf()
method to find the index of the last occurrence of the delimiter ('|'
), and then extracts a part of the string starting from that index using substring()
.Pros and Cons
Split()
Pros:
Cons:
Substring
Pros:
substring()
.Cons:
Library
There is no library used in this benchmark. However, note that some JavaScript engines might provide additional optimization features or built-in methods for these operations (e.g., String.prototype.split()
and String.prototype.substring()
).
Special JS Feature/Syntax
None are explicitly mentioned in this benchmark. However, it's worth noting that the use of the lastIndexOf()
method is a relatively modern JavaScript feature introduced in ECMAScript 2015.
Other Alternatives
In this specific case, there aren't many alternatives to these two approaches. Other options might include:
s1.match('|')
) for string splitting.indexOf()
method instead of lastIndexOf()
for finding the index of a delimiter.However, it's worth noting that these alternative methods might not be as efficient or expressive as the original two approaches.