루프 한번 돌 때마다 계속 메모리 할당 및 해제가 이뤄지는 줄 알고 일부러 밖으로 빼냈었는데 그렇지도 않고 다른 여러가지 이유로 좋은 행동이 아니었네요
By creating variables inside loops, you ensure their scope is restricted to inside the loop. It cannot be referenced nor called outside of the loop.
This way:
If the name of the variable is a bit "generic" (like "i"), there is no risk to mix it with another variable of same name somewhere later in your code (can also be mitigated using the -Wshadow warning instruction on GCC)
The compiler knows that the variable scope is limited to inside the loop, and therefore will issue a proper error message if the variable is by mistake referenced elsewhere.
Last but not least, some dedicated optimization can be performed more efficiently by the compiler (most importantly register allocation), since it knows that the variable cannot be used outside of the loop. For example, no need to store the result for later re-use.
The variable is allocated once, when the function is called. In fact, from an allocation perspective, it is (nearly) the same as declaring the variable at the beginning of the function. The only difference is the scope: the variable cannot be used outside of the loop. It may even be possible that the variable is not allocated, just re-using some free slot (from other variable whose scope has ended).
예에전 C에서나 선언부 함수앞에 몰아넣던거 아닌가
그런거 말고 변수를 루프 밖에 선언하느냐 안에서 하느냐 얘기인 듯 재활용
보통 가독성을 우선해서 가급적 변수 범위를 제한할수록 좋은 거고, 성능이 그렇게 중요하면 벤치마크하기 전까진 판도라의 상자 아닐까 싶음.
지역변수는 함수스택에 위치해서 스택 포인터 레지스터의 값만 이동시키면 되기 때문에 비용이 아주 크지 않아서 그냥 써도 됨 미세하게 차이는 있겠지만
그래도 메모리 할당은 루프 안에서 반복하기 보다는 밖에서 한번만 하는게 좋겠지