var s1 = "foo|bar|test";
var n1 = s1.split('|');
console.log(n1.slice(1).join('|'))
var pip = s1.indexOf('|');
console.log(s1.substring(pip));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.split | |
Substring |
Test name | Executions per second |
---|---|
Array.split | 40642.7 Ops/sec |
Substring | 34666.9 Ops/sec |
Let's dive into the explanation of what is being tested in this JavaScript microbenchmark.
Overview
The benchmark tests two different approaches to splitting a string: Array.split
and String.substring
. The test inputs are identical, with a single string s1
containing multiple pipe (|
) characters. The goal is to measure which approach performs better in terms of execution time.
Approaches being compared
There are two primary approaches being tested:
Array.split()
: This method splits the input string into an array of substrings, using the pipe character as the separator. The resulting array is then processed further (in this case, slice(1)
is used to remove the first element and join('|')
is used to concatenate the remaining elements).String.substring()
: This method returns a new string that starts at the specified index (0-based) and continues to the end of the original string.Pros and Cons
Array.split()
:
filter()
, map()
)String.substring()
:
Array.split()
Other considerations
Library usage
None of the code uses any external libraries beyond the standard JavaScript library.
Special JS feature or syntax
There is no special JavaScript feature or syntax being used in this benchmark. However, it's worth noting that modern JavaScript engines often include experimental features (e.g., const
support) or ES6+ features like let
and const
. This benchmark does not use any of these features.
Alternatives
Other alternatives for string splitting include:
Array.split()
.Keep in mind that these alternatives are not typically used for simple string splitting tasks and may have additional overhead or complexity.