本文介紹了在循環中聲明變量是否有任何開銷?(C++)的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我只是想知道如果你做這樣的事情是否會降低速度或效率:
I am just wondering if there would be any loss of speed or efficiency if you did something like this:
int i = 0;
while(i < 100)
{
int var = 4;
i++;
}
聲明 int var
一百次.在我看來好像會有,但我不確定.這樣做會更實用/更快嗎:
which declares int var
one hundred times. It seems to me like there would be, but I'm not sure. would it be more practical/faster to do this instead:
int i = 0;
int var;
while(i < 100)
{
var = 4;
i++;
}
或者它們在速度和效率方面是否相同?
or are they the same, speedwise and efficiency-wise?
推薦答案
局部變量的棧空間通常在函數作用域內分配.所以循環內部不會發生堆棧指針調整,只是將 4 分配給 var
.因此,這兩個代碼段具有相同的開銷.
Stack space for local variables is usually allocated in function scope. So no stack pointer adjustment happens inside the loop, just assigning 4 to var
. Therefore these two snippets have the same overhead.
這篇關于在循環中聲明變量是否有任何開銷?(C++)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!