12

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.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Dennis Spierenburg
  • 613
  • 2
  • 6
  • 16
  • 3
    Set up a perf test to find out yourself. In order for anyone here to answer they would have to do the same thing – charlietfl May 22 '18 at 09:11
  • My question too. Live example: https://jsben.ch/HNunY and got this weird result, in Chrome 97 `replaceAll` is slower, and with big strings even more slow! – MMMahdy-PAPION Jan 20 '22 at 05:26

2 Answers2

18

I ran a JSPerf to test which is faster, and as I thought, the replace function is around 40-50% faster (I tested on Chrome 66):

https://jsperf.com/replace-vs-split-join-seblor

Plus you get a memory gain, because split creates an array.


2021 edit:

Since this answer is still being read, here is a snippet so you can test the performance in your browser:

function runBenchmark() {
  console.log('Starting...');
  const string = 'Hello World';
  const replaceRegex = / /g;
  new Benchmark.Suite()
    .add('split & join', () => {
      let newString = string.split(' ').join('_');
    })
    .add('replace regex', () => {
      let newString = string.replace(replaceRegex, "_");
    })
    .add('replaceAll', () => {
      let newString = string.replaceAll(" ", "_");
    })
    .add('replaceAll with regex', () => {
      let newString = string.replaceAll(replaceRegex, "_");
    })
    .on('cycle', (event) => {
      console.log(String(event.target));
    })
    .run({ async: true });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script>
<button onclick="runBenchmark()">Run Benchmark</button>

On chrome 94, regex replacing seem to be twice as fast as splitting and joining.

Seblor
  • 6,947
  • 1
  • 25
  • 46
9

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.

Lorenz Merdian
  • 722
  • 3
  • 14
  • 4
    "it does not matter at all" that's a wrong way to think about it. The correct sentence is "it doesn't matter in the scope of your project". Imagine if every application out there took your approach to writing code. All those "small" performance optimizations might sum up to a higher CPU use overall. And by extension higher power use, if that's something you care about. I'm not saying you're completely wrong, I'm saying it is a bad idea to tell someone (possibly new to programming) outright that they should not care about such things. – Krzaku Oct 21 '20 at 15:25