I have made two tests because I wanted to test performance on two different implementations of trying to find a number in a string.
This is my code:
[TestMethod]
public void TestMethod1()
{
string text = "I want to find the number (30)";
var startNumber = text.IndexOf('(');
var trimmed = text.Trim(')');
var number = trimmed.Substring(startNumber).Trim('(');
Assert.AreEqual("30", number);
}
[TestMethod]
public void TestMethod2()
{
string text = "I want to find the number (30)";
var lambdaNumber = text.Where(x => Char.IsNumber(x)).ToArray();
var joined = string.Join("", lambdaNumber);
Assert.AreEqual("30", joined);
}
The result is that TestMethod2 (with the lamda expression) is faster than TestMethod1. According to the test explorer.
TestMethod1 = 2ms TestMethod2 = <1ms
If I try to add a StopWatch in each test, TestMethod1 is by far the fastest.
How can I properly test the performance of this behaviour?
EDIT:
I appreciate the fact that the methods do not perform the same operation. Therefore I created the following in stead:
[TestMethod]
public void TestMethod1()
{
var sw = new Stopwatch();
sw.Start();
var number = string.Empty;
var counter = 0;
while (counter < 100000)
{
number = string.Empty;
string text = "I want to find the number (30)";
foreach (var c in text.ToCharArray())
{
int outNumber;
if (int.TryParse(c.ToString(), out outNumber))
number += c.ToString();
}
counter++;
}
sw.Stop();
Assert.AreEqual("30", number);
}
[TestMethod]
public void TestMethod2()
{
var sw = new Stopwatch();
sw.Start();
var joined = String.Empty;
var counter = 0;
while (counter < 100000)
{
string text = "I want to find the number (30)";
var lambdaNumber = text.Where(x => Char.IsNumber(x)).ToArray();
joined = string.Join("", lambdaNumber);
counter++;
}
sw.Stop();
Assert.AreEqual("30", joined);
}
According to the StopWatch the results are the following: TestMethod1 = 19ms TestMethod2 = 7ms
Thank you for all the replies