简体   繁体   English

性能问题:String.split然后在数组上行走,还是RegExp?

[英]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? 哪一个会更快,首先通过String.split拆分文本,然后在结果数组上行走或直接通过reg exp遍历整个文本并在路上构造最终数组?

虽然这已经晚了两年半,但希望这有助于为未来的任何观众提供一些信息: http//jsperf.com/split-join-vs-regex-replace (包括多个浏览器的基准测试结果,以及功能基准代码本身)

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 ;) 嗯,获得答案的最好方法是花2分钟然后写一个循环,两次都做两千次并检查萤火虫看哪一个更快;)

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. 在使用MXHR时,我不得不优化大量的字符串重写,根据我的经验,普通的String方法比当前浏览器中的RegExps快得多。 Use RegExps on the shortest Strings possible and do everything you possibly can with String methods. 在最短的字符串上使用RegExps,并使用String方法尽一切可能。

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. 这很难看,不管你信不信,它比高负荷下的等效RegExp要快得多。

I expect that using split() will be much faster. 我希望使用split()会更快。 It depends upon many specifics, number of lines vs. length, complexity of regex, etc. 它取决于许多细节,行数与长度,正则表达式的复杂性等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM