AL <AL@discussions.microsoft.comwrote:
I usually stick to the convention of not declaring variables in my bodies of
"loops" (including foreach)
ie
int x;
for (int i = 0; i < 10; i++) {
x = ...
}
as opposed to
for (int i = 0; i < 10; i++) {
int x = ...
}
No, the latter is generally nicer - it avoids "polluting" the namespace
of available variables, and shows that you genuinely intend to only use
the variable within the loop.
I've heard that in Java declaring variables within loops can cause problems
Until I see any evidence of of it, I'd be very sceptical of that.
Certainly in the all the time I've written Java, I've never run into
any issues like that.
and I've tried to create some metrics to compare the difference in C# code
between prior to the loop and within the loop.
My results indicated that there was no difference.
I'd like to get a better idea from any one else as to whether my conclusion
is acurate or there is some form of performance hit.
No, there isn't a performance hit unless you're able to initialize the
variable once and then leave it initialized to the same value. Even
then I'd take the readability improvement of the latter style over the
*possible* slight performance improvement of the former until I'd
proved it was a bottleneck.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too