javascriptsplitperformance

Javascript Split Performance


I'm sure you've all seen code like this in JS:

var args = 'now later today tomorrow'.split(' ')

Anyone know why that's faster than this:

args = ['now', 'later', 'today', 'tomorrow']

(I don't know the answer to this, but I can verify by timing in the console that splitting is faster)


Solution

  • I would be surprised if .split() was faster; why do you think it is?

    I made this perf demo and it shows it's not faster.

    https://web.archive.org/web/20150602025321/https://jsperf.com/split-performance


    Testing in Firefox 139.0 32-bit on Windows NT 10.0 64-bit

    Test Code Ops/sec
    Split var args = 'now later today tomorrow'.split(' ') 15,739,447
    ±13.29%
    86% slower
    Array args = ['now', 'later', 'today', 'tomorrow'] 101,481,757
    ±1.88%
    fastest

    screenshot of results table above showing Array is faster than Split