Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split and join function or the replace function

Tags:

javascript

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.

like image 836
Dennis Spierenburg Avatar asked May 22 '18 09:05

Dennis Spierenburg


People also ask

What is the difference between the split and the join methods?

You can use split() function to split a string based on a delimiter to a list of strings. You can use join() function to join a list of strings based on a delimiter to give a single string.

What is the use of replace and split function of string?

It returns another copy of the original string by replacing all occurrences of a specific substring with the specified value (or substring). The original string remains unaltered. If the value to be replaced is not found in the original string, a copy of the original string is returned.

What is difference between join and split function in Python?

the split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Python String join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator.

Why are split and join useful?

This process of payload splitting and response aggregation is called a Split-Join pattern. Split-Joins are particularly useful for optimizing overall response times in scenarios where payloads delivered by faster systems are being directed to responding services on slower systems.


2 Answers

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, "_");
    })
    .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.

like image 89
Seblor Avatar answered Nov 14 '22 21:11

Seblor


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.

like image 36
Lorenz Merdian Avatar answered Nov 14 '22 21:11

Lorenz Merdian