Search code examples
javascript

Split and join function or the replace function


I'm curious which function is faster in JavaScript and I can't find a solution to this problem. Lets take a simple string and replace all spaces with underscores.

let string = 'Hello World';
let newString = string.split(' ').join('_');
//newString: Hello_World

The other way to solve this is the replace function:

let string = 'Hello World';
let newString = string.replace(/ /g,"_");
//newString: Hello_World

Both ways (in my opinion) are fine to read. I'm wondering which way is faster at this moment (May 2018). I found some answers but these are outdated and I was wondering if they have increased the performance of newer browsers.


Solution

  • In my personal experience: it does not matter at all, unless you're writing absolute high-performance JavaScript (like 10k ops/ frame). Writing an meaningful perftest is also very hard, due to compiler optimizations, which are really complex und make it hard to understand what's actually measured.

    In another post, there is a hint, that a loop would be the fastest, but i doubt it's really relevant in practice.

    Which is more efficient .replace() or .split().map().join()

    Watching the results of the the jsperf test by @Seblor, you see, that there are many hundred thousand invocations per second possible. So, performance is not really an issue.

    Split-Join: 1,381,976 ±6.79% 25% slower

    Replace 1,856,450 ±7.22% fastest

    So: Just go with what you like more.