Loop Optimizations for Arrays and Strings

  • Thread starter Thread starter jwgoerlich
  • Start date Start date
J

jwgoerlich

Hello group,

I have been reviewing Microsoft's webinars and documents on C# JIT
optimizations. One, Designing .Net Class Libraries, said that this
code:

for (i = 0; i < a.Length; i++) { ... }

Is faster than this:

int l = a.Length;
for (i = 0; i < l; i++) { ... }

For arrays. This was because of how the CLR handles bounds checking. Is
the same true for strings and StringBuilders?

J Wolfgang Goerlich
 
I have been reviewing Microsoft's webinars and documents on C# JIT
optimizations. One, Designing .Net Class Libraries, said that this
code:

for (i = 0; i < a.Length; i++) { ... }

Is faster than this:

int l = a.Length;
for (i = 0; i < l; i++) { ... }

For arrays. This was because of how the CLR handles bounds checking. Is
the same true for strings and StringBuilders?

Based on a simple test with .NET 2.0 then I would say:
String - yes
StringBuilder - no

But the second code style is not to be recommended. It is
the programmer trying to do something that the optimizer
should do.

It was once a common style of manual optimizing code, but it
will disappear within the next 10 years. Similar to usage
of the register keyword in C.

Arne
 
Thank you, sir.
Based on a simple test with .NET 2.0 then I would say:
String - yes
StringBuilder - no

But the second code style is not to be recommended. It is
the programmer trying to do something that the optimizer
should do.

It was once a common style of manual optimizing code, but it
will disappear within the next 10 years. Similar to usage
of the register keyword in C.

Arne
 

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