Skip to content Skip to sidebar Skip to footer

Performance Question: String.split And Then Walk On The Array, Or Regexp?

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 whole tex

Solution 1:

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.

Solution 2:

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)

Solution 3:

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

Post a Comment for "Performance Question: String.split And Then Walk On The Array, Or Regexp?"