Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 text via a reg exp and construct the final array on the way?

like image 574
BYK Avatar asked Jun 08 '09 20:06

BYK


People also ask

Is regex faster than string split?

Regex will work faster in execution, however Regex's compile time and setup time will be more in instance creation. But if you keep your regex object ready in the beginning, reusing same regex to do split will be faster. String.

Is regex faster than split Javascript?

split() to be faster than regex.

Can we use regex in split a string?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.

Is regex faster than split Python?

Split is most of the time faster than a regex , but it depends on the complexity of the regex.


2 Answers

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.

like image 81
Micah Snyder Avatar answered Nov 11 '22 07:11

Micah Snyder


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)

like image 35
Andrew Odri Avatar answered Nov 11 '22 08:11

Andrew Odri