elzacho wrote On 09/23/05 16:17,:
I would like to (and commonly do) define my variables in the most
specific scope I can. For example...
int foo(int a, int b, int c)
{
/* don't declare temp here if we can help it */
...
for (i = 0; i < max; i++)
{
/* declare here */
int temp;
...
/* use temp */
}
}
But my concern is, does the declaration take up cpu time? One can
imagine that temp could be a huge array or max could be a large number.
In this case, if the declaration maps to any cpu time when compiled,
this could lead to a significant performance drop.
So, is there a difference in the machine code between declaring all of
your variables at outer most scope or inner most scope? My impressions
on C are that it makes does not impose how this is handled, rather that
this is a compiler issue, but I am not sure how much the standards
dictate this. Thought I would pass it by some experts.
The language Standard doesn't say much about speed or
about implementation techniques, so your question will have
different answers on different platforms. What follows is
"typical" but by no means universal:
- There is likely to be no cost for creating `temp' in
the example you've given, in the sense that the loop
will take no longer.
- There could be a space cost if you have several such
`temp' variables in different scopes. The compiler
might devote different memory cells to each `temp',
when it would have allocated just one cell to a single
`temp' at a higher level.
- ... but on the other hand there might actually be a
"negative cost" if by restricting the scope of `temp'
you make it easier for the compiler to discover that
it and `jcounter' never exist at the same time, and
so can share the same storage -- perhaps even the same
CPU register.
For ordinary scalars like your `temp' the penalties or
benefits are likely to be so small that they're difficult to
measure. But if `temp' is something more complicated the
picture may change:
- If `temp' is large, it would be wise to ensure that the
compiler allocates just one batch of memory for it. If
you have other large `temp' objects of the same type in
other disjoint inner scopes, the compiler might assign
separate memory locations to each occurrence.
- If `temp' has an initializer, the initialization will
occur on every iteration of the loop. If you don't
need that to happen, don't pay for it.
- If `temp' is a C99 variable-length array (`int temp[n]'
where `n' is variable), there may be additional costs
to allocate and deallocate memory on each iteration.
Recommendation: Simple scalars and other small objects
are good candidates for the treatment you like, especially
if they don't need initializers. Large objects, objects with
initializers, and VLAs are probably not such good candidates.
"Not necessarily. Bless you, it all depends!"
-- Pitti-Sing
--
Er*********@sun.com