JavaScript 변수는 외부 또는 내부 루프를 선언합니까?
AS3에서는 성능 향상을 위해 루프 외부의 모든 변수를 초기화해야한다고 생각합니다. JavaScript에서도 마찬가지입니까? 어느 쪽이 더 좋고 / 빠른 / 가장 좋은 방법입니까?
var value = 0;
for (var i = 0; i < 100; i++)
{
value = somearray[i];
}
또는
for (var i = 0 ; i < 100; i++)
{
var value = somearray[i];
}
없습니다 차이 절대적으로 자바 스크립트 또는 ActionScript의 의미 나 성능은.
var
파서에 대한 지시문이며 런타임에 실행되는 명령이 아닙니다 . var
함수 식별자 (*)에서 특정 식별자가 한 번 이상 선언 된 경우 블록에서 해당 식별자의 모든 사용은 로컬 변수를 참조합니다. 루프 내부, 루프 외부 또는 둘 다에 value
선언 되는지 여부 는 차이가 없습니다 var
.
결과적으로 가장 읽기 쉬운 것을 작성해야합니다. Crockford에 동의하지 않습니다. 모든 변수를 함수의 맨 위에 두는 것이 항상 가장 좋은 것입니다. 변수가 코드 섹션에서 임시로 사용되는 경우 var
해당 섹션에서 선언 하는 것이 더 좋으므로 섹션은 독립형이며 복사하여 붙여 넣을 수 있습니다. 그렇지 않으면 리팩토링하는 동안 관련 코드를 따로 따로 이동하지 않고 몇 줄의 코드를 새 함수에 복사하여 붙여 넣으면 var
실수로 전역이 생길 수 있습니다.
특히:
for (var i; i<100; i++)
do something;
for (var i; i<100; i++)
do something else;
Crockford는 두 번째를 제거하도록 권장합니다 var
(또는 var
s를 제거 하고 var i;
위 의 작업을 모두 수행 하십시오). 그러나 IMO var
는 함수의 맨 위에 쉽게 잊혀지는 여분의 코드 를 두지 않고 모든 관련 코드를 함께 유지하면서 두 가지를 모두 유지하는 것이 더 쉽습니다.
개인적으로 필자 var
는 독립적 인 코드 섹션에서 변수의 첫 번째 할당으로 같은 함수의 다른 부분에 동일한 변수 이름을 별도로 사용하는지 여부 를 선언하는 경향이 있습니다. 나에게 var
전혀 선언 하지 않는 것은 바람직하지 않은 JS 사마귀입니다 (변수를 기본값으로 로컬로 설정하는 것이 좋을 것입니다). JavaScript에서 ANSI C의 [이전 개정] 제한 사항을 복제하는 것이 나의 의무라고 생각하지 않습니다.
(* : 중첩 함수 본문 이외)
이론적으로는 언어에 블록 범위가없고 함수 범위 만 있기 때문에 JavaScript에서 아무런 차이가 없어야합니다.
성능 인수에 대해서는 잘 모르겠지만 Douglas Crockford는 여전히 var
함수 문에서 첫 번째 명령문이어야한다고 권장합니다 . JavaScript 프로그래밍 언어에 대한 코드 규약 에서 인용 :
JavaScript에는 블록 범위가 없으므로 블록에 변수를 정의하면 다른 C 계열 언어에 익숙한 프로그래머가 혼동 될 수 있습니다. 함수 상단에 모든 변수를 정의하십시오.
다음 예에서 볼 수 있듯이 그는 요점이 있다고 생각합니다. 함수 상단에 변수를 선언하면 독자가 변수 i
가 for
루프 블록 의 범위에 있다고 생각하는 것을 혼동해서는 안됩니다 .
function myFunction() {
var i; // the scope of the variables is very clear
for (i = 0; i < 10; i++) {
// ...
}
}
ECMA-/Javascript
언어 hoists
기능의 정상에 어디 선언 된 모든 변수입니다. 이 언어가 있기 때문이다 않는 이 function scope
와 않습니다 하지 가 block scope
다른 언어 C와 같은처럼.
이라고도합니다 lexical scope
.
당신이 같은 것을 선언하면
var foo = function(){
for(var i = 0; i < 10; i++){
}
};
이것은 hoisted
:
var foo = function(){
var i;
for(i = 0; i < 10; i++){
}
}
So it does not make any difference in performance (But correct me if I'm totally wrong here).
A much better argument for not declaring a variable somewhere else than at the top of a function is readability. Declaring a variable within a for-loop
might lead to the wrong assumption that this variable can only be accessed within the loop body, which is totally wrong. Infact you can access that variable anywhere within the current scope.
Next year, all browsers will have JS engines that precompile the code so the performance difference (which comes from parsing the same block of code again and again plus executing the assignment) should become negligible.
Also, never optimize for performance unless you have to. Keeping variables close to the place where you need them the first time keeps your code clean. On the negative side, people who are used to languages with block scopes might be confused.
I just did a simple test in Chrome. Try the fiddle in your browser and see the results
var count = 100000000;
var a = 0;
console.log(new Date());
for (var i=0; i<count; i++) {
a = a + 1
}
console.log(new Date());
var j;
for (j=0; j<count; j++) {
a = a + 1;
}
console.log(new Date());
var j;
for (j=0; j<count; j++) {
var x;
x = x + 1;
}
console.log(new Date());
Result is that the last test takes ~8 seconds and the previous 2 are only ~2 seconds. Very repeatably and regardless of order.
So, this proves to me, that one should always declare the vars outside of the loop. Curious case to me is the first one where I declare i
in the for() statement. This one appears to be just as fast as the 2nd test where I pre-declare the index.
Another consideration, now that we have let
and const
in ES2015, is that you can now scope variables specifically to the loop block. So unless you will need the same variable outside the loop (or if each iteration depends on an operation done to that variable in the previous iteration), it's probably preferable to do this:
for (let i = 0; i < 100; i++) {
let value = somearray[i];
//do something with `value`
}
JavaScript is a language written at the bottom by C or C++, I'm not very sure which one it is. And one of its purpose is saving the lavour of handling internal memory. Even in C or C++, you won't have to worry about whether it will consume a lot of resources when variables are declared inside a loop. Why should you worry about it in JavaScript?
Well, that depends on what you're trying to achieve... if value
suppose to be only a temporary variable inside loop block then it's much clearer to use second form. It's also more logical and verbose.
It Doesn't make difference if you declare variables inside or outside of for loop. Below is the sample code to test.
function a() {
console.log('Function a() starts');
console.log(new Date());
var j;
for (j=0; j<100000000; j++) {
var x;
x = x + 1;
}
console.log(new Date());
console.log('Function a() Ends');
}
a()
function b() {
console.log('Function B() starts');
console.log(new Date());
var a;
var j;
for (j=0; j<100000000; j++) {
a = a + 1;
}
console.log(new Date());
console.log('Function B() Ends');
}
b()
The results showed in my case
Function a() starts
VM121:3 Thu Apr 12 2018 15:20:26 GMT+0530 (India Standard Time)
VM121:9 Thu Apr 12 2018 15:20:26 GMT+0530 (India Standard Time)
VM121:10 Function a() Ends
VM121:14 Function B() starts
VM121:15 Thu Apr 12 2018 15:20:26 GMT+0530 (India Standard Time)
VM121:21 Thu Apr 12 2018 15:20:26 GMT+0530 (India Standard Time)
VM121:22 Function B() Ends
Thank you -- MyFavs.in
The question here is basically to declare a var inside a loop. Just think what happens if you do this:
var a = 30;
var a = 50;
var a = 60;
Do you think this is right? No ... because you don't want to declare a variable so many times. When you declare a variable inside a loop isn't it declaring as many times the loop runs? Obviously it will slap you when you are in 'use strict' mode. People have disagreed with Crockford without thinking about the original question.
So it is always good to declare variables on top -- 1. For readability, 2. Making good habits.
In regards to performance after running test on Chrome, Firefox, and jsperf on a Linux OS there does appear to be a performance difference between the declaration of variables in a loop and out of a loop. It is a small difference but this is also compounded by the amount of iterations and the amount of variable declarations.
Therefore for best performance I would have to suggest declaring variables outside the loop. Or better yet declare your variables in line. See example.
// inline
for (var ai = 0, al = 100000000, av; ai < al; ai++) {
av = av + 1;
}
// outside
var bv;
var bl = 100000000;
for (var bi = 0; bi < bl; bi++) {
bv = bv + 1;
}
Notice how the variable 'al' and 'av' are in the for loop declaration line. This inline declaration has provided me with consistently better performance. Even over the declaration of variables outside the loop. Again the performance difference is really small.
https://jsperf.com/outside-inline-for-loop-ase/1
참고URL : https://stackoverflow.com/questions/3684923/javascript-variables-declare-outside-or-inside-loop
'Programing' 카테고리의 다른 글
.AsNoTracking ()의 차이점은 무엇입니까? (0) | 2020.05.06 |
---|---|
OpenGL에서 프리미티브를 와이어 프레임으로 어떻게 렌더링합니까? (0) | 2020.05.06 |
Windows 용 명령 줄 svn? (0) | 2020.05.06 |
단일 종속성의 모든 전이 종속성을 제외 (0) | 2020.05.06 |
전체 문서 HTML을 문자열로 얻는 방법? (0) | 2020.05.06 |