const strings = [ 'onclick', 'onwheel', 'onresize', 'noclick', 'nowheel', 'noresize' ];
function getStrings() {
return strings;
}
const regex = /^on/
for( let i = 0; i < 10000; i++ ) {
getStrings().forEach( str => regex.test( str ) );
}
for( let i = 0; i < 10000; i++ ) {
getStrings().forEach( str => str.slice(0, 2) === 'on' );
}
for( let i = 0; i < 10000; i++ ) {
getStrings().forEach( str => str[ 0 ] === 'o' && str[ 1 ] === 'n' );
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex | |
slice | |
array |
Test name | Executions per second |
---|---|
regex | 613.4 Ops/sec |
slice | 7282.7 Ops/sec |
array | 2431.9 Ops/sec |
Let's dive into the world of JavaScript benchmarks.
What is being tested?
The provided benchmark compares three different approaches to test whether a given string starts with the substring 'on'. The three approaches are:
/^on/
regex pattern to match strings that start with 'on'.slice()
method to extract the first two characters of each string and then comparing them to 'on' using the equality operator (===
).===
).Options compared
The benchmark compares the performance of these three approaches in terms of the number of executions per second.
Pros and cons of each approach
Library usage
The benchmark uses the strings
array created in the "Script Preparation Code" section, which contains 10 strings. This array is used as input for each test case.
Special JavaScript feature or syntax
None mentioned.
Benchmark results
The latest benchmark results show that:
Alternatives
If you need more performance or a different approach, consider using:
Keep in mind that benchmarking results may vary depending on the specific use case, hardware, and software environment.