efficiency of declaring local variables

  • Thread starter Thread starter Oliver Corona
  • Start date Start date
O

Oliver Corona

I am wondering if anyone has any insights on the performance benefit (or
detriment) of declaring local variables instead of referencing members. Is
allocating memory for a new variable more efficient than repeatedly
referencing the member in a loop?

Maybe using a string isn't the best example, but hopefully you get the
idea!


* example (referencing member):

Dim s As String = "this is a test"
For i As Integer = 0 To s.Length
If s.Chars(i) = "x"c Then
Console.WriteLine(s.Chars(i))
End If
Next i


* example (creating new variable):

Dim s As String = "this is a test"
Dim chars As Char() = s.Chars
For i As Integer = 0 To s.Length
If chars(i) = "x"c Then
Console.WriteLine(chars(i))
End If
Next i
 
Oliver,
I would recommend you reference the member, then if you find that has a
performance issue change it.

I rarely try to 'second guess' the VB.NET or C# compiler itself or the JIT
compiler.

Normally you should write correct straight forward programs first, then
when your routine is determined to have a performance problem, change that
routine to be better optimized.

In other words, don't waste your time optimizing a routine that you don't
even know it has a problem.


The following articles provide information on writing .NET code that
performs well.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/fastmanagedcode.asp

http://msdn.microsoft.com/library/d...y/en-us/dndotnet/html/highperfmanagedapps.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/vbnstrcatn.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbtchperfopt.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/dotnetperftechs.asp

Hope this helps
Jay
 
Back
Top