Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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

This comment has been minimized.

Copy link

@wrzwicky wrzwicky commented Jan 13, 2019

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