-1

I want to compare the following two ways of reversing a string:

Version 1:

function reverseString(str){
  return str.split('').reverse().join('');
}

Version 2:

function reverseString(str){
  if(str.length == 1) return str;
  return str[str.length - 1] + (reverseString(str.slice(0,str.length - 1)));
}

How can I reliably determine which pattern is more efficient?

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 2
    Did you try to benchmark both so you could tell the difference in terms of performance ? – m.raynal Apr 08 '19 at 17:47
  • Benchmark them and find out. Also, recommended reading: https://ericlippert.com/2012/12/17/performance-rant/ –  Apr 08 '19 at 17:52
  • https://stackoverflow.com/questions/7128057/measuring-and-benchmarking-processing-power-of-a-javascript-engine-in-a-browser and https://stackoverflow.com/questions/111368/how-do-you-performance-test-javascript-code – Teemu Apr 08 '19 at 17:53

2 Answers2

0

Based off of this jsperf, your first function (number 1) appears to perform quicker while testing on Chrome 73 with windows 10. It is worth noting that the difference computed here is negligible.

Note that you may create your own benchmarks using sites such as jsperf.

Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33
0

The recursive one seems a bit slower. I would suggest a third option: a simple for loop and string concatenation.

NB: the downside of the recursive solution is that it can run into a stack overflow when the string is long.

You can use benchmark.js to measure performance:

function reverseString1(str) {
    return str.split('').reverse().join('');
}
function reverseString2(str) {
    if (str.length == 1) return str;
    return str[str.length - 1] + (reverseString2(str.slice(0,str.length - 1)));
}
function reverseString3(str) {
    let result = "";
    for (let i = str.length; i--;) result += str[i];
    return result;
}

// An input string of 200 characters:
let str = "asirjsmpfuenndlsuegi".repeat(20);
console.log("Tests...");
const suite = new Benchmark.Suite("reverse string");
suite.add("split&join", () => reverseString1(str))
     .add(" recursive", () => reverseString2(str))
     .add("  for-loop", () => reverseString3(str))
     .on('cycle', (event) => console.log(String(event.target)))
     .on('complete', () => 
         console.log('Fastest is: ' + suite.filter('fastest').map('name')))
     .run({ 'async': true });
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.js"></script>
trincot
  • 317,000
  • 35
  • 244
  • 286