确保拆分后数组大于 1 的正确方法是什么?
我目前正在做一个大项目(我的意思是很多流程),我节省的每一毫秒都意味着很多(从长远来看),所以我想确保我以正确的方式做这件事。
那么,确保数组大于 1 的最佳方法是什么?
- a) 使用 indexOf(),然后如果结果不同于 -1,则 split()
- b) 拆分(无论是否字符存在),然后仅当 array.length 大于 1
- c) 上面未列出的另一个
I am currently doing a big project (by big I mean, many processes) where every millisecond I save means a lot (on the long run), so I want to make sure I am doing it the right way.
So, what is the best way to ensure you will have an array greater than 1?
- a) use indexOf(), then if result is different than -1, split()
- b) split (regardless if characters exist), then do stuff ONLY if the
array.length is greater than 1 - c) another not listed above
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 jsPerf ,似乎省略
.indexOf()
是比包含超过 500,000 次迭代的效率提高大约 23%(每秒11.67
与8.95
操作):没有
indexOf()
:使用
.indexOf()
:http://jsperf.com/split-and-split-indexof
编辑
嗯...如果以下行是:
<一个href="http://jsperf.com/split-and-split-indexof-with-indexof-check" rel="nofollow">http://jsperf.com/split-and-split-indexof-with-indexof -check
或任何其他比较,它似乎要快得多(大约 69%)。
我认为这种情况的唯一原因是,在每个变量上运行
.split()
将对每个值执行两个函数(查找,然后分离),而不是在必要时只执行一个函数。请注意,最后一部分只是一个猜测。Using jsPerf, it appears that omitting
.indexOf()
is roughly 23% more efficient that including it over 500,000 iterations (11.67
vs.8.95
operations per second):Without
indexOf()
:With
.indexOf()
:http://jsperf.com/split-and-split-indexof
EDIT
Hmm... If the following line is:
http://jsperf.com/split-and-split-indexof-with-indexof-check
Or any other comparison, it's seemingly quite a bit faster (by about 69%).
The only reason I can think this is the case is that running
.split()
on every variable will perform two functions on each value (find, then separate), instead of just one when necessary. Note, this last part is just a guess.我们可以看到,即使有一些东西可以分割,最好的结果也来自于对一个值进行 indexOf 测试。但与 100% 的项目不需要拆分的情况相比,这种改进仍然更差。因此,当您有更多的项目需要拆分时,测试带来的好处就会减少(正如预期的那样)。因此,这实际上取决于用例,因为额外的代码会占用内存并使用资源。
http://jsperf.com/split-and-split-indexof/2
We can see that even when there is something to split the best results come from doing the indexOf test against a value. Still the improvement is worse that the cases where 100% of items don't need a split. Thus as you have more items needing to be split testing returns less benefit (as would be expected). So it really depends on the use case since the extra code takes up memory and uses resources.
http://jsperf.com/split-and-split-indexof/2
(b) 显然比 (a) 更高效,因为 split 使用与 indexOf 相同的逻辑,并且如果确实有超过 2 个元素,则不需要重复该逻辑。我想不出更有效的方法。
(b) is obviously more efficient than (a) because split uses the same logic as indexOf and that logic will not need to be repeated if there are indeed more than 2 elements. i cannot think of a more efficient way.