var arr = new Map()
let prev=""
for (let i = 0;i<1000;++i){
prev+="ABC:";
arr.set(+i,prev);
}
function process(s){
return s.slice(0,s.lastIndexOf(':'))
}
for (const [key,value] of arr){
let s = process(arr.get(key))
while(s.length){
s = process(s)
}
arr.delete(key)
}
var arr = new Map()
let prev=[]
for (let i = 0;i<1000;++i){
prev =[prev, 'ABC']
arr.set(+i,prev);
}
function process(s){
return s.slice(0,s.length-1)
}
for (const [key,value] of arr){
let s = process(arr.get(key))
while(s.length){
s = process(s)
}
arr.delete(key)
}
var arr = new Map()
let prev=[]
for (let i = 0;i<1000;++i){
prev = prev.concat('ABC')
arr.set(+i,prev);
}
function process(s){
return s.slice(0,s.length-1)
}
for (const [key,value] of arr){
let s = process(arr.get(key))
while(s.length){
s = process(s)
}
arr.delete(key)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
String concat | |
Array spread | |
Array with concat |
Test name | Executions per second |
---|---|
String concat | 37.3 Ops/sec |
Array spread | 18.4 Ops/sec |
Array with concat | 17.7 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared, and some pros and cons of each approach.
Benchmark Overview
The benchmark compares three ways to concatenate strings (or simulate string concatenation) in JavaScript:
slice()
method with a substring of the original string....
) to create a new array from an existing one.concat()
method to concatenate arrays.Test Cases
Each test case has two parts:
process()
function that takes a string as input and returns a modified version of it (in this case, by removing characters from the end of the string).Comparison
The comparison between these three approaches will likely measure:
Pros and Cons
Here are some pros and cons of each approach:
Pros:
Cons:
Pros:
Cons:
Pros:
Cons:
Library and Special JS Features
None of the test cases use any libraries or special JavaScript features beyond what's already described.