Optimize Assignments |
||||||||
Created Date: 4/23/2008 | ||||||||
Last Modified Date: 4/23/2008 | ||||||||
Believe it or not, just optimizing the assignments can lead to a much faster performance. Whenever use the increment function (C# only) otherwise the += sign is better than a = a + 1. This is true because the code does not have to fetch twice the same memory block (once for loading the value and the second one to save).
public void OptimizeAssignmentTest1() { int Loops = 100000000; int ReturnValue = 0; DateTime StartTime = DateTime.Now; for (int i = 0; i < Loops; i++) { ReturnValue = ReturnValue + 1; } DateTime Endtime = DateTime.Now; System.Console.WriteLine("ReturnValue = ReturnValue + 1 - \t" + Endtime.Subtract(StartTime).TotalSeconds.ToString()); } public void OptimizeAssignmentTest2() { int Loops = 100000000; int ReturnValue = 0; DateTime StartTime = DateTime.Now; for (int i = 0; i < Loops; i++) { ReturnValue += 1; } DateTime Endtime = DateTime.Now; System.Console.WriteLine("ReturnValue += 1 - \t" + Endtime.Subtract(StartTime).TotalSeconds.ToString()); } public void OptimizeAssignmentTest3() { int Loops = 100000000; int ReturnValue = 0; DateTime StartTime = DateTime.Now; for (int i = 0; i < Loops; i++) { ReturnValue++; } DateTime Endtime = DateTime.Now; System.Console.WriteLine("ReturnValue++ - \t" + Endtime.Subtract(StartTime).TotalSeconds.ToString()); }
|
||||||||
:: Better Coding Practices :: |