Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

Is there any overhead to declaring a variable within a loop? (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++;
}

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...