Search code examples
c#optimizationmicro-optimizationpremature-optimizationspeed-test

How to test what method implementation runs faster


While the question check if input is type of string has been closed two of the answers spiked a micro-optimization question in my mind: which of the below two solutions would perform better?

Reed Copsey provided a solution using Char.IsLetter:

string myString = "RandomStringOfLetters";
bool allLetters = myString.All( c => Char.IsLetter(c) );

Adapted solution using regex from Mark Byers:

string s = "RandomStringOfLetters";
bool allLetters = Regex.IsMatch(s, "^[a-z]+$", RegexOptions.IgnoreCase);

Not wanting to just ask the question of either Reed or Mark I thought I'd write a quick test to determine which performed better. Problem is I haven't done a lot of code optimization (I tend to put code readability above all else).

Other than taking a timestamp before and after the run of each, what are some other (better?) options of determining which solution runs faster?

Edit

I modified Martin's answer to work with Console.WriteLine(...) and ran it as a console application. Not sure exactly how LinqPad runs applications but the results were about the same:

41
178

Solution

  • You'll want to do this, measuring the runtimes using a Stopwatch. Also, here are a few very important things to keep in mind when profiling:

    1. Always run your test more than 1 time. The first time you run it, there will be overhead from the JIT, and the timings may be misleading. Running many times and taking the average is a good approach (I'll often run a test like this 100,000 times, for example.)
    2. Always run your test with a full Release build, outside of the Visual Studio hosting process. (By default, you can use Ctrl+F5 for this.) The Visual Studio host dramatically impacts timings.