Replacement performance in string

10

I need to do some bulk replacement with Javascript. For my specific problem, let's assume I need to replace a specific substring. I need to change every occurrence of "blue" to "green."

So, I have two ways to do it:

var foo = pegaTexto(); // imagine que isso retorna uma string qualquer;
foo = foo.replace("azul", "verde");

Or:

var foo = pegaTexto();
foo = foo.replace(new RegExp("azul"), "verde");

In my view, the only practical use of a regular expression would be to specify a flag (to say for example if the search should be global), but in my case I am omitting the flags from the expression constructor.

I have a question, however, regarding performance in these two different ways.

Does using regular expression have any impact on performance?

How can I measure this?

    
asked by anonymous 10.02.2014 / 22:07

2 answers

18

You can use jsperf.com , where you can set up tests to test different variations.

I did a test and gave me 13 ~ 15% slower with RegExp.

The code I used:

var texto = 'amarelo verde encarnado azul branco';

// com regex    
var regex = new RegExp("azul");
for(var i = 0; i < 50000; i++){
   var resultado = texto.replace(regex, "verde");
}

// com replace de string
for(var i = 0; i < 50000; i++){
   var resultado = texto.replace("azul", "verde");
}

The fastest way for this function seems to be split / join - break the string to each word and rejoin it with the new word. Credit for the response of the @utluiz.

var novaString = texto.split('palavraAntiga').join('palavraNova');
    
10.02.2014 / 22:17
7

I've added two more replacement techniques that do not use regular expressions to jsperf original of Sergio.

split / join

var resultado = texto.split('azul').join('verde');

indexOf

var pos = texto.indexOf('azul');
var ultpos = 0;
var resultado = '';
while (pos >= 0) {
    resultado += texto.substring(ultpos, pos) + 'verde';
    ultpos = pos + 4;
    pos = texto.indexOf('azul', pos + 4);
}
if (ultpos < texto.length) {
    resultado += texto.substring(ultpos, texto.length);
}

Results

By analyzing the results in other browsers by other users, I noticed that there is no consensus on the fastest method.

See the chart as I write:

In summary:

  • split/join wins in Chrome
  • indexOf wins in Firefox and Opera
  • regex wins in IE: /
11.02.2014 / 15:16