How to check which method implementation is faster

While the question of checking whether the input is a string type has been closed. Two answers raised the question of micro-optimization: which of the following two solutions will work best?

Reed Copsie provided a solution usingChar.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 Reed or Mark a question, I thought I would write a quick test to determine which ones are better. The problem is that I did not do much code optimization (I usually prefer to read the code above all the others).

Except that you make a timestamp before and after running each of them, what are some other (better?) Options for determining which solution works faster?

Edit

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

41
178
+3
source share
6 answers

You will want to do this by measuring runtime using Stopwatch . In addition, here are some very important things to consider when profiling:

  • . , , JIT , . , - (, , , 100 000 ).
  • , Visual Studio. ( Ctrl + F5.) Visual Studio .
+7

LINQPad , (, Dump() - Console.WriteLine(...), ).

, LINQ :

System.Diagnostics.Stopwatch stopwatch = new Stopwatch();

stopwatch.Start();
for (int i = 0; i < 100000; i++)
{
 string myString = "RandomStringOfLetters";
 bool allLetters = myString.All( c => Char.IsLetter(c) );
}
stopwatch.Stop();
stopwatch.ElapsedMilliseconds.Dump();

stopwatch.Reset();

stopwatch.Start();
for (int i = 0; i < 100000; i++)
{
 string s = "RandomStringOfLetters";
 bool allLetters = Regex.IsMatch(s, "^[a-z]+$", RegexOptions.IgnoreCase);
}
stopwatch.Stop();
stopwatch.ElapsedMilliseconds.Dump();

:

47 
196
+2

System.Diagnostics.Stopwatch, .

, , , JIT, . - - , .

0

System.Diagnostics.Stopwatch.

StopWatch , ,

0

, : -

  • , , AMD/Intel/other, 32-bit/64-bit,...

  • .NET, ( )

  • ( )

  • StopWatch

  • Monitor memory usage for everyone, as this can have a greater impact on the rest of your application. Saving multiple cycles by increasing memory consumption and increasing garbage collection activity is often a poor “optimization."

This may give you some idea of ​​what is faster in practice, at least for current compiler releases. Repeat with each new version of the compiler.

0
source

Source: https://habr.com/ru/post/1755792/


All Articles