Performance question: String.split and then walk on the array, or RegExp?

前端 未结 3 718
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 19:47

I\'ll do some work on a line separated string. Which one will be faster, to split the text via String.split first and then walk on the resultant array or directly walk the w

相关标签:
3条回答
  • 2021-01-01 20:10

    While this is 2½ years late, hopefully this helps shed some light on the matter for any future viewers: http://jsperf.com/split-join-vs-regex-replace (Includes benchmarks results for multiple browsers, as well the functional benchmark code itself)

    0 讨论(0)
  • 2021-01-01 20:17

    Well, the best way to get your answer is to just take 2 minutes and write a loop that does it both ways a thousand times and check firebug to see which one is faster ;)

    I've had to optimize a lot of string munging while working on MXHR and in my experience, plain String methods are significantly faster than RegExps in current browsers. Use RegExps on the shortest Strings possible and do everything you possibly can with String methods.

    For example, I use this little number in my current code:

    var mime = mimeAndPayload.shift().split('Content-Type:', 2)[1].split(";", 1)[0].replace(' ', '');
    

    It's ugly as hell, but believe it or not it's significantly faster than the equivalent RegExp under high load.

    0 讨论(0)
  • 2021-01-01 20:18

    I expect that using split() will be much faster. It depends upon many specifics, number of lines vs. length, complexity of regex, etc.

    0 讨论(0)
提交回复
热议问题