Compiler optimization question

  • Thread starter Thread starter Lloyd Dupont
  • Start date Start date
L

Lloyd Dupont

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);

will the code do a bound checking on the array on every single access to
buf or will it recognises that N, and buf.Length are constant and
optimize to only one bounds checking?
 
Lloyd Dupont said:
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);

will the code do a bound checking on the array on every single access to
buf 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);
}

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.
 
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 said:
Lloyd Dupont said:
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);

will the code do a bound checking on the array on every single access to
buf 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);
}

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.
 
Back
Top