在JavaScript循环外声明变量可以获得速度和内存吗? [英] Speed and memory benefit from declaring variable outside JavaScript loop?

查看:80
本文介绍了在JavaScript循环外声明变量可以获得速度和内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#也有类似的问题,但我们没有看到任何关于JavaScript的问题。

There are similar questions for C#, but we didn't see any for JavaScript.

在循环中声明变量是否被接受?

Is it accepted practice to declare variables inside a loop?

假设循环为200次迭代。

Assume a loop of 200 iterations.

在样本1上使用样本2是否存在性能要求(内存和速度) ?我们正在使用jQuery循环。它提高了代码的可读性,使我们能够将var保留在循环中,但是如果它不是最佳实践,或者会导致性能大幅下降或内存使用率增加,我们将进行切换。

Is there a performance imperative (memory and speed) to using sample 2 over sample 1? We're using jQuery to loop. It improves code readability for us to keep the var inside the loop, but we'll switch if it's not a best practice or will result in materially slower performance or higher memory usage.

**Sample 1:**
$(this).each( function() {
   var i = $(some_div).clone();
   *** edit i ***
   $(another_div).append( i );
});



**Sample 2:**
var i = null;
*** edit i ***
$(this).each( function() {
   i = $(some_div).clone();
   $(another_div).append( i );
});


推荐答案

样本1(内部变量)更快:
http://jsperf.com/variable-outside-faster

Sample 1 (variable inside) is faster: http://jsperf.com/variable-outside-faster

但这种差异不值得关注。

But the difference is not worth enough to care about.

这篇关于在JavaScript循环外声明变量可以获得速度和内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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