Javascript:多次运行函数时出现神秘的滞后
以下函数仅返回文档中具有指定标记名的元素。由于某种原因,在连续调用该函数时,它的执行变得越来越慢。我已经彻底测试了它以及原因中的 for-loop 行,但我不明白为什么这会导致连续调用变慢。
function getElementsByTagName2(tagName){
var arr=new Array();
var elems=document.getElementsByTagName(tagName);
for(var i=0, len=elems.length; i!=len; arr.push(elems[i++]));
return arr
}
编辑:更改变量名称以取悦 user257493。
EDIT1:刚刚测试了 jQuery,它也有同样的问题。但退化程度很小。
The following function simply returns an of elements with the specified tagname in the document. For some reason on successive calls to the function the execution of it gets slower and slower.. I have tested it thoroughly and the for-loop line in the cause, but I don't understand why that would cause a slow down on successive calls.
function getElementsByTagName2(tagName){
var arr=new Array();
var elems=document.getElementsByTagName(tagName);
for(var i=0, len=elems.length; i!=len; arr.push(elems[i++]));
return arr
}
EDIT: Changed variable names to please user257493.
EDIT1: Just tested jQuery and it has the same issue. The degradation is minor though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我已经测试了你的代码,它似乎运行得很好。
我的结果(迭代 -> 花费的时间(找到的 div):
1. Firefox:
0-> 1524(已找到 102)
1-> 1534(已找到 102)
2-> 1518(已找到 102)
3-> 1528(已找到 102)
4-> 1535(已找到 102)
...
15-> 1513(已找到 102)
16-> 1512(已找到 102)
17-> 1513(已找到 102)
18-> 1513(已找到 102)
19-> 1518(发现 102)
2。 Chrome:
0-> 387(已找到 102)
1-> 283(已找到 102)
2-> 268(已找到 102)
3-> 272(已找到 102)
4-> 271(已找到 102)
...
15-> 270(已找到 102)
16-> 279(已找到 102)
17-> 267(已找到 102)
18-> 287(已找到 102)
19-> 272(已找到 102)
I've tested Your code and it seems to run just fine.
My results (iteration -> time taken (found divs):
1. Firefox:
0 -> 1524 (found 102)
1 -> 1534 (found 102)
2 -> 1518 (found 102)
3 -> 1528 (found 102)
4 -> 1535 (found 102)
...
15 -> 1513 (found 102)
16 -> 1512 (found 102)
17 -> 1513 (found 102)
18 -> 1513 (found 102)
19 -> 1518 (found 102)
2. Chrome:
0 -> 387 (found 102)
1 -> 283 (found 102)
2 -> 268 (found 102)
3 -> 272 (found 102)
4 -> 271 (found 102)
...
15 -> 270 (found 102)
16 -> 279 (found 102)
17 -> 267 (found 102)
18 -> 287 (found 102)
19 -> 272 (found 102)
函数运行之间发生了什么? DOM 如何变化?由于返回元素数量增加,每个过程花费的时间逐渐变长的可能性有多大?另外,推送速度很慢。这也有效,并且可能会加快你的速度 - 我在重复执行中没有显示任何延迟。
What goes on between the runs of your function? How does the DOM change? What's the likelihood that each takes successively longer because you've got an increased number of return elements? Also, push is slow. This also works and might speed you up a bit - I show no delays in repeated executions.
尝试直接分配数组元素,而不使用推送。
Try to assign the array elements directly, without push.
Prototype to-array 方法是否也有同样的问题?
Does the Prototype to-array method have the same problem?