var str = ""
var arr = []
for (let i = 0; i < 100000; ++i) {
str += 'ABC::';
arr.push('ABC');
}
function process(s){
return s.slice(0,s.lastIndexOf(':'))
}
while (str.length) {
str = process(str);
}
function process(a){
return a.slice(0,a.length-2)
}
while (arr.length) {
arr = process(arr);
}
let str = ""
for (let i = 0; i < 100000; ++i) {
str += 'ABC:';
}
function process(a){
return a.slice(0,a.length-2)
}
while (arr.length) {
arr = process(arr);
}
let str = ""
for (let i = 0; i < 100000; ++i) {
str += 'ABC:';
}
function process(s){
return s.slice(0,s.lastIndexOf(':'))
}
while (str.length) {
str = process(str);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
String slice | |
Array slice | |
Array with creation | |
String with creation |
Test name | Executions per second |
---|---|
String slice | 153434336.0 Ops/sec |
Array slice | 119252856.0 Ops/sec |
Array with creation | 1756.4 Ops/sec |
String with creation | 238.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The provided JSON represents a benchmark that compares three different approaches to slice strings and arrays in JavaScript:
slice()
method on a string object (str.slice(0, str.lastIndexOf(':'))
).slice()
method on an array object (arr.slice(0, arr.length-2)
).let arr = []; for (let i = 0; i < 100000; ++i) { arr.push('ABC'); }
).Options Compared
The benchmark compares the performance of these three approaches:
slice()
on a string object.slice()
on an array object.Pros and Cons
Here's a brief analysis of the pros and cons of each approach:
slice()
is designed for arrays.Library and Syntax Considerations
In this benchmark, no libraries are used, and special JavaScript features (e.g., let
and const
) are not mentioned. However, it's worth noting that the use of let
and const
instead of traditional variable declarations can affect the performance of some operations.
Other Alternatives
Other approaches to slice strings and arrays in JavaScript might include:
substr()
method, which is similar to slice()
, but returns a new string object instead of an array.split()
and join()
methods to extract substrings from strings or concatenate arrays.Keep in mind that these alternatives might have different performance characteristics and use cases, which are not explored in this benchmark.