Re: Repeated instantiation of a variable / performance?

From: Michiel Salters (Michiel.Salters_at_logicacmg.com)
Date: 07/02/04


Date: 2 Jul 2004 04:21:39 -0700


"Robert Sturzenegger" <yob.stuyzeneggey@ziksuhy.ch> wrote in message news:<40e4e382$0$26640$5402220f@news.sunrise.ch>...
> // Code sequence A
> for (int i = 0; i < 10; ++i) {
> int k = something();
> // some more code which uses k
> }
>
> // Code sequence B
> int k;
> for (int i = 0; i < 10; ++i) {
> k = something();
> // some more code which uses k
> }
>
> Are the two sequences exactly the same in terms of performance, or has the
> repeated instanciation of k in sequence A a certain cost compared with the
> single one instantiation in sequence B?

With current compilers, exactly the same. In both cases compilers simply
reserve sizeof(int) bytes on the stack. This happens at compile time.

> What about if k were of a class type?

In this case, it's unpredicatble. The first case has 10 ctor calls and
10 dtor calls. The second case has one ctor call, one dtor, and 10
assignments. The naive assumption would be that the first is more
expensive, but exceptio-safe assignments are usually implemented as
{ create temporary, swap contents, destroy temporary } which means
it includes both a ctor and dtor call. Then the second case is
more expensive.

Other cases may be even more complex. E.g. if k has type std::string,
the relative performance depends critically on the length of the
10 strings returned by something().

Regards,
Michiel Salters



Relevant Pages