[Solved] What is the difference between declaring an object outside and inside of a loop


When you declare the object inside the loop, a new object will be created on each iteration and the exising one destroyed at the end of each iteration. This is because the object will have a scope inside the {}.

When you declare it outside, a single object is created and you work with that, But when you put it inside a loop, a new object is created and destroyed on each iteration, which will affect the speed.

That is, when you use

MyObject obj;

for(int i = 0; i < n; i ++)
{
    obj.func(vector<float>);
}

you crate only one object. But when you use

for(int i = 0; i < n; i ++)
{
    MyObject obj;
    obj.func(vector<float>);
}

you create and destroy n objects. That will increase the execution time. So, it’s better to use the first.

7

solved What is the difference between declaring an object outside and inside of a loop