It is generally better (for performance) to offload
frequently used member vars into local variables,
although often times the compiler optimizer does it one
better and uses registers for countres/ptrs etc. Problem
comes in when there is a call to a function/method inside
a loop and/or the body of code within the loop is just
too big and the optimizer can no longer use registers to
hold ptrs/ctrs. This is my experience from unmanaged
code; I am pretty sure that CLR is not that much
different, since it will compile your source into native
code.
Having said all this, and being more of a code
maintenance proponent than a performance freek, I would
not use local vars unless I was doing a very CPU
intensive algorithm involving nested
iterations/recursions/etc. This is because on 1 Gig plus
processors, the performace hit is practically negligable,
but readability suffers quite a bit and can lead to
stupid mistakes such as updating a local var expecting
the unerlying (original) variable to change. I have
recently done a performance measurement comparing various
access techniques/methods (OLE DB vs native vs ODBC) on a
large database. I was iterating a million or so records
within a loop and parsing a text LOB (up to 1 meg or so)
containing within each record. The code was not very
efficient, so rewrote it to make sure that the code did
not have an impact on measurements of the data base.
Guess what - no difference, maybe a few milliseconds or
so (out of several minutes) in native VC6 code, which I
credit to a pretty good VC6 optimizer and fast CPU (P4
2G).
Now if you are a true performance fanatic, you should
also change your for statment to use a previously
declared local var instead of s.Length comparison in your
for statement...
My 2 cents...
-----Original Message-----
I am wondering if anyone has any insights on the
performance benefit (ordetriment) of declaring local variables instead of
referencing members.Is allocating memory for a new variable more efficient
than repeatedlyreferencing the member in a loop?
Maybe using a string isn't the best example, but
hopefully you get theidea!
* example (referencing member):
String s = "this is a test";
for (int i=0; i<s.Length; i++) {
if (s.Chars[i] == 'x') {
Console.WriteLine(s.Chars[i]);
}
}
* example (creating new variable):
String s = "this is a test";
char[] chars = s.Chars;
for (int i=0; i<s.Length; i++) {
if (chars[i] == 'x') {
Console.WriteLine(chars[i]);
}
}
.