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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top