性能问题:String.split然后在数组或RegExp上遍历? [英] Performance question: String.split and then walk on the array, or RegExp?

查看:59
本文介绍了性能问题:String.split然后在数组或RegExp上遍历?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将对行分隔的字符串做一些工作.哪一个会更快,首先通过String.split分割文本,然后遍历结果数组,或者直接通过reg exp遍历整个文本,然后构造最终的数组?

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?

推荐答案

好吧,获得答案的最好方法是花2分钟并编写一个循环,执行这两种方法一千次,并检查萤火虫以查看哪个一个更快;)

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 ;)

在使用MXHR时,我不得不优化许多字符串调试方法,根据我的经验,普通的String方法在当前浏览器中的运行速度比RegExps快得多.在可能的最短字符串上使用RegExps,并使用String方法做所有可能的事情.

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(' ', '');

这很丑陋,但是不管您相信与否,它在高负载下比同等的RegExp快得多.

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

这篇关于性能问题:String.split然后在数组或RegExp上遍历?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆