問(wèn)題描述
我只是想知道如果你做這樣的事情是否會(huì)降低速度或效率:
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
一百次.在我看來(lái)好像會(huì)有,但我不確定.這樣做會(huì)更實(shí)用/更快嗎:
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++;
}
或者它們?cè)谒俣群托史矫媸欠裣嗤?
or are they the same, speedwise and efficiency-wise?
推薦答案
局部變量的棧空間通常在函數(shù)作用域內(nèi)分配.所以循環(huán)內(nèi)部不會(huì)發(fā)生堆棧指針調(diào)整,只是將 4 分配給 var
.因此,這兩個(gè)代碼段具有相同的開(kāi)銷(xiāo).
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.
這篇關(guān)于在循環(huán)中聲明變量是否有任何開(kāi)銷(xiāo)?(C++)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!