13

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.

2
  • 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 Commented May 22, 2018 at 9:11
  • My question too. Live example: jsben.ch/HNunY and got this weird result, in Chrome 97 replaceAll is slower, and with big strings even more slow! Commented Jan 20, 2022 at 5:26

3 Answers 3

19

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.

Sign up to request clarification or add additional context in comments.

Comments

10

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.

3 Comments

"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.
My project involves looking at text provided and remove parts of it, this "text" could be 10 characters long or 10,000 lines long. So, I'd say it matters to me.
@Krzaku did you miss the "unless you're writing absolute high-performance JavaScript" part? Because this answer is frankly refreshingly pragmatic. Under-the-hood implementations/optimizations change all the time, and chasing that can be a fools errand. What is 7% faster today might be 25% slower tomorrow. As for someone new to learning programming, "worry about making it work first, then worry about making it fast" is a good adage.
1

I'm seeing this answer relatively high on Google, while the other answers are right in your use case, they do not hold up in other use cases.

Regex does not scale well, just taking the example benchmark by Seblor, but replacing the string "hello world" by the book Othello by William Shakespeare (I'm not linking a code, the string is 5730 lines long, but you are welcome to follow this link that has the full document: https://shakespeare.mit.edu/othello/full.html)

The benchmark results are a 40% reduction in ops:

split & join x 1,486 ops/sec ±0.55% (12 runs sampled)
replace regex x 916 ops/sec ±0.26% (63 runs sampled)
replaceAll x 906 ops/sec ±0.71% (9 runs sampled)
replaceAll with regex x 910 ops/sec ±0.72% (63 runs sampled)

The more nuanced answer is that you need to verify those points:

  • How long is your string? the longer the string, the less efficient the regex will be. Running a regex on a small string will be faster than split and join, but on a long string, split and join will almost always outperform the regex.

  • How complex is your regex? Matching simple spaces is fast, but the more complicated it will be, the more expensive the regex will become. This is the basis of ReDOS attacks that slow down your server by sending strings that will hog down a poorly made regex.

And finally, how can you verify this? the tool https://regex101.com/ can help you verify the complexity and speed of a regex, by giving you the number of steps required to match your regex: more steps = slower.

1 Comment

This should be set as the answer, at the very least it needs more upvotes than "0".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.