Question

Why

for (int i=0; i<1e6; ++i)
{
    ofstream o("out.txt",ios_base::app);
    o<<i;
}

is slower than

ofstream o("out.txt",ios_base::app);
for (int i=0; i<1e6; ++i)
{
    o<<i;
    o.flush()
}

? I was tought that the first is faster because the visibility of o is less in the first case than in the second one and if the initialization of o would cost too much, the compiler would optimize it out and create a binary code basically based on the second one. In generally, what is the recommendation on defining variables inside or outside a loop? In what circumstances is valid that Variables should be defined as late as possible!?

Can I improve the runtime of a program by adding {} symbols around variables that I don't want to use later in order to reduce visibility or the compiler can maintain these information easily and effectively so there's no need to fill up my code with {}'s?

Was it helpful?

Solution

In the first loop, you construct and destroy the ofstream each time through the loop. The constructor opens the file; the destructor flushes the buffer and closes the file. These operations are not cheap.

In the second loop, you construct the ofstream once, use that one object through all iterations of the loop, then destroy it once (when it goes out of scope later). You only open the file once and you only close the file once.

The compiler cannot transform the first loop into the second (or vice-versa) because they are not equivalent: opening and closing files are actions that have external effects.

In general, yes, you should always declare objects with as limited a scope as possible. But there are limits to this--when construction or destuction is expensive, you should avoid constructing more objects than you need to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top