Avoid intermediate arrays (parsing strings) to make you Javascript fast

alexander-nenashev

Alexander Nenashev

Posted on May 18, 2024

Avoid intermediate arrays (parsing strings) to make you Javascript fast

In the previous post there was argued why we should avoid intermediate arrays for performance in cases like filter/map chains.

I'd say String#split() is heavily overused when parsing strings. A common scenario is to get the first word in a string. The first thought is to split a string into words and get the first one. Again, an intermediate array is created, worse, only the first element is used, the rest is just waste of space and time. Use String#indexOf() and String#slice() instead:

let $length = 1;
const str = Array.from({length: $length + 1}, () => 'test').join(' ');

// @benchmark Array#split
str.split(' ')[0];

// @benchmark String#indexOf
str.slice(0, str.indexOf(' '));

// @benchmark regex
str.match(/^\S+/)[0];

` Chrome/125
-----------------------------------------------------------------------------------------------
>                       n=1        |       n=10        |       n=100       |       n=1000      
String#indexOf   ■ 1.00x x100m 972 | ■ 1.00x x100m 959 | ■ 1.00x  x10m  94 |  ■ 1.00x x100m 967
regex              2.99x  x10m 291 |   3.06x  x10m 293 |   3.07x  x10m 289 |    2.96x  x10m 286
Array#split        6.49x  x10m 631 |  22.52x   x1m 216 | 165.96x x100k 156 | 1509.82x  x10k 146
----------------------------------------------------------------------------------------------- `
` Firefox/126
------------------------------------------------------------------------------------------------
>                       n=1        |       n=10        |       n=100       |       n=1000       
String#indexOf   ■ 1.00x x100m 105 | ■ 1.00x x100m 120 | ■ 1.00x x100m 108 |   ■ 1.00x x100m 109
regex             35.90x  x10m 377 |  27.83x  x10m 334 |  33.15x  x10m 358 |    32.11x  x10m 350
Array#split       39.05x  x10m 410 | 105.00x   x1m 126 | 944.44x x100k 102 | 10000.00x  x10k 109
------------------------------------------------------------------------------------------------ `
Enter fullscreen mode Exit fullscreen mode

Open in the playground

💖 💪 🙅 🚩
alexander-nenashev
Alexander Nenashev

Posted on May 18, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related