Skip to content

Instantly share code, notes, and snippets.

@nicStuff
Created January 8, 2019 15:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicStuff/ddf9e647453c850aed711671e6aa6b2d to your computer and use it in GitHub Desktop.
Save nicStuff/ddf9e647453c850aed711671e6aa6b2d to your computer and use it in GitHub Desktop.
// simple benchmark for reversing a string in js - source https://medium.com/quick-code/5-ways-to-reverse-a-string-in-javascript-466f62845827
function reverseFor(str){
let reversed = "";
for (var i = str.length - 1; i >= 0; i--){
reversed += str[i];
}
return reversed;
}
function reverseArray(str){
return str.split("").reverse().join("");
}
function reverseSpread(str){
return [...str].reverse().join('');
}
function reverseReduce(str){
return str.split("").reduce((rev, char)=> char + rev, '');
}
function reverserecursion(str){
if(str === ""){
return str
}else{
return reverserecursion(str.substr(1)) + str[0]
}
}
let string = 'hello world'
let iterations = 100000
let bmarkData = [
{
'function': reverseFor,
'name': 'reverseFor',
'time': 0
},
{
'function': reverseArray,
'name': 'reverseArray',
'time': 0
},
{
'function': reverseSpread,
'name': 'reverseSpread',
'time': 0
},
{
'function': reverseReduce,
'name': 'reverseReduce',
'time': 0
},
{
'function': reverserecursion,
'name': 'reverserecursion',
'time': 0
},
]
bmarkData.forEach((data) => {
let before = Date.now()
for (let i = 0; i < iterations; i++) {
data.function(string)
}
let after = Date.now()
data.time = (after - before)
})
console.log(bmarkData)
@wrzwicky
Copy link

Here's the numbers I got on an i7 laptop; time is milliseconds for 1 million iterations. Timing is closer than I would have expected, but as you might expect, reverseFor is the winner.

  • name: 'reverseFor', time: 235
  • name: 'reverseArray', time: 677
  • name: 'reverseSpread', time: 750
  • name: 'reverseReduce', time: 262
  • name: 'reverserecursion',time: 420

Test string is pretty short, so I replaced it with the comment from the first line of the script. Again, time is milliseconds for 1 million iterations. Surprisingly, reverseReduce wins this time.

  • name: 'reverseFor', time: 2144
  • name: 'reverseArray', time: 4821
  • name: 'reverseSpread', time: 6643
  • name: 'reverseReduce', time: 1893
  • name: 'reverserecursion',time: 5514

Now we just need an analysis of memory usage for these.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment