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?
views:
364answers:
2
+1
A:
I expect that using split() will be much faster. It depends upon many specifics, number of lines vs. length, complexity of regex, etc.
RedFilter
2009-06-08 20:09:06
Thanks for taking time to answer. I also expected the native methods to be faster but nothing can be better than an experience for this question IMO. Thanks anyway =)
BYK
2009-06-08 20:17:46
That answer IS based on experience :) as dfltr said, you need to experiment for your particular case.
RedFilter
2009-06-08 20:50:45
Well the problem is, I do not know the string size and the regexp will be a simple \n|\r matcher if I use regexp. Any more suggestions? =) (BTW sorry for thinking it was an estimate ;))
BYK
2009-06-08 20:54:44
+6
A:
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.
dfltr
2009-06-08 20:11:03
I considered testing via Firebug but actually didn't trust the time measurement of JS. Thank you very much for your answer with a supporting example ;)
BYK
2009-06-08 20:16:24
So don't trust firebug - create and compare a couple of date objects as well
annakata
2009-06-08 20:18:44
Well I do not trust the JS Date objects itself since when(some time ago) I tried to measure performance, although it claimed it was milliseconds precise, it was always returning multiples of seconds. This is why I do not trust it.
BYK
2009-06-08 20:21:20
Note also that different implementations of JavaScript (Firefox, Internet Explorer, WebKit, etc.. ) will have different perforamnces.
Adam N
2009-06-08 20:54:21
Good point Adam N. I actually started to implement something conditional. What about this? I mean depending on the string size, and the browser, I'll switch btw both methods.
BYK
2009-06-08 20:59:02