String Reversing Algorithm Performance In JavaScript

Wherever performance is the key factor, choosing the right algorithm, (in a very unbiased fashion,) is a very crucial factor. And generally for reversing string in JavaScript applications, I endorse this petite string reversal algorithm using Array.reverse() method.

We often see developers having the choice of multiple information paths and multiple algorithms for a particular routine. So, what is the factor by which one should decide upon the correct algorithm? “Profiling” is the word.

Readability of code comes as a secondary factor as in most cases you can cover up for the less readability using good inline documentation and by encapsulating blocks of complex codes in a series of sub-routines, apparently making it simpler.

(A) JavaScript string reversing using Array.reverse()

It is just one line of code to reverse a string using the Array.reverse() method. One first needs to split the string using null as separator. This causes the string to be split into an array of characters. This array is now reversed and is converted back to string using Array.join() method.

String.prototype.reverse = function() {
    return this.split('').reverse().join('');

All the three methods used here (split, reverse and join) are native JavaScript methods.

(B) Classic JavaScript string reversing method

This method is pretty straightforward. It simply runs a loop and copies each character in a string to another string in reverse order.

String.prototype.reverse = function() {
    var i, s='';
    for(i = this.length; i >= 0; i--) {
        s+= this.charAt(i);
    return s;

This method is very popular and a large number of JavaScript applications use this method to reverse strings.

Comparing string reversing algorithms

In an interpreted execution environment, such as JavaScript, any native method scores higher in performance than custom methods. We would see the validation of this statement as we compare the above two examples.

We have performed our test using strings of various lengths and measured the average execution time of 10 calls.

String Size (b) Method A (ms) Method B (ms) Difference (A-B %)
0 0.027 0.005 -440
1 0.032 0.007 -357.14
2 0.033 0.009 -266.67
4 0.035 0.01 -250
8 0.036 0.014 -157.14
16 0.04 0.02 -100
32 0.047 0.032 -46.88
64 0.06 0.058 -3.45
128 0.087 0.106 17.92
256 0.139 0.211 34.12
512 0.488 0.266 40.625
1024 0.417 0.793 47.41
2048 9.574 18.362 47.86
4096 20.822 39.962 47.9
8192 43.856 81.774 46.369
16384 98.404 186.113 47.13

The above table clearly shows that for strings of approximate length less than 64 characters, the classic algorithm is a lot faster: almost double the speed for small strings. However, for large strings, our new and sexy one-liner algorithm is almost consistently 50% faster.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.