In a for-loop in C#, which of the following codeblocks are the best performance wise? Or is there no difference?
The diffenrence is whether the condition is saved in a local variable or read directly from an object.
Option 1
float maxDepth = 0;
int maxnumber = 0;
for (int i = 0; i < defects.Total; i++)
{
if (defects[i].Depth > maxDepth)
{
maxDepth = defects[i].Depth;
maxnumber = i;
}
}
Option 2
float maxDepth = 0;
int maxnumber = 0
int defectNumber = defects.Total;
for (int i = 0; i < defectNumber; i++)
{
if (defects[i].Depth > maxDepth)
{
maxDepth = defects[i].Depth;
maxnumber = i;
}
}
I’m sorry if this question have been asked a lot, but I couldn’t find it anywhere.
Anders
For all such questions you can use
System.Diagnostics.Stopwatchlike this.Then you got exact information. (The best way is to take several runs and use the mean value)