Programming in C#, as in many languages, provides a limitless way to write
applications. So many different programming techniques can vary in your
application's speed and efficiency. Learning how to determine which coding
techniques are faster is an essential skill.
The simple structure to test out fast C# code run is this:
- Set up all variables required
- Set up a DateTime start variable to mark the beginning of the test
- Initialize a for loop with the code to be tested inside (the amount of
trials should be set up to make the total execution time last an appropriate
amount)
- Mark the ending time on a DateTime end variable
- Subtract the starting time to the ending time
- The difference can then be compared to other tests
An optional
step is to divide the total time it took to execute the C# code and divided by
the amount of times the for loop ran.I personally like to compare the total
execution times since it reduces the variation in the results.
Usually the first time the code is executed the source code will run slower
than normal, so try to run several tests and average out the results.
Also I recommend to test source code from within Visual Studio (the debuggin
environment in other words) since source code that runs with the debugger runs a
bit slower. This gives a nicer window to compare different bits of source code
against their speeds.
Remember that the final Release version of your application will be optimized
by the compiler (inline code and such) and will almost always run faster than
the debugging version.