just curiosity because I guess there isn't much I could do about it....

if I write
byte[] buf = ...;
int N = ...;
for(int i=0; i<N; i++)
do(buf[i]);

will the code do a bound checking on the array on every single access to
buf[i] or will it recognises that N, and buf.Length are constant and
optimize to only one bounds checking?

--
If you're in a war, instead of throwing a hand grenade at the enemy, throw
one of those small pumpkins. Maybe it'll make everyone think how stupid war
is, and while they are thinking, you can throw a real grenade at them.
Jack Handey.

Re: Compiler optimization question by Jon

Jon
Tue Sep 06 13:05:55 CDT 2005

Lloyd Dupont <ld@NewsAccount.galador.net> wrote:
> just curiosity because I guess there isn't much I could do about it....
>
> if I write
> byte[] buf = ...;
> int N = ...;
> for(int i=0; i<N; i++)
> do(buf[i]);
>
> will the code do a bound checking on the array on every single access to
> buf[i] or will it recognises that N, and buf.Length are constant and
> optimize to only one bounds checking?

It's less likely to do it with the code above than if you do:

for (int i=0; i < buf.Length; i++)
{
do (buf[i]);
}

However, an even better way would be:

foreach (int x in buf)
{
do (x);
}

Readability is almost always far more important than micro-optimisation
like this anyway.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Re: Compiler optimization question by Lloyd

Lloyd
Tue Sep 06 18:26:51 CDT 2005

Allright.
Anyway I was using N because I didn't want to use buf.Length for the simple
reason I DON'T compare the whole buffer.

It was not micro-optimization, it was plain program logic ;-)


"Jon Skeet [C# MVP]" <skeet@pobox.com> wrote in message
news:MPG.1d87eae1a9ff0cd298c672@msnews.microsoft.com...
> Lloyd Dupont <ld@NewsAccount.galador.net> wrote:
>> just curiosity because I guess there isn't much I could do about it....
>>
>> if I write
>> byte[] buf = ...;
>> int N = ...;
>> for(int i=0; i<N; i++)
>> do(buf[i]);
>>
>> will the code do a bound checking on the array on every single access to
>> buf[i] or will it recognises that N, and buf.Length are constant and
>> optimize to only one bounds checking?
>
> It's less likely to do it with the code above than if you do:
>
> for (int i=0; i < buf.Length; i++)
> {
> do (buf[i]);
> }
>
> However, an even better way would be:
>
> foreach (int x in buf)
> {
> do (x);
> }
>
> Readability is almost always far more important than micro-optimisation
> like this anyway.
>
> --
> Jon Skeet - <skeet@pobox.com>
> http://www.pobox.com/~skeet
> If replying to the group, please do not mail me too