Skip to content

Instantly share code, notes, and snippets.

@polatengin
Last active February 26, 2018 12:23
Show Gist options
  • Save polatengin/20456c4700311bd30f3d19c865a85173 to your computer and use it in GitHub Desktop.
Save polatengin/20456c4700311bd30f3d19c865a85173 to your computer and use it in GitHub Desktop.
C# String.IndexOf, String.Contains, Regex.IsMatch(), Regex.IsMatch() Compiled performans karşılaştırma
public void InvokeTests()
{
TestAndPrint(() => { StringIndexOfTest("dolor"); }, nameof(StringIndexOfTest) + "-NoMatch");
TestAndPrint(() => { StringIndexOfTest("engin"); }, nameof(StringIndexOfTest) + "-Match");
TestAndPrint(() => { StringContainsTest("dolor"); }, nameof(StringContainsTest) + "-NoMatch");
TestAndPrint(() => { StringContainsTest("engin"); }, nameof(StringContainsTest) + "-Match");
TestAndPrint(() => { RegexIsMatchTest("dolor"); }, nameof(RegexIsMatchTest) + "-NoMatch");
TestAndPrint(() => { RegexIsMatchTest("engin"); }, nameof(RegexIsMatchTest) + "-Match");
TestAndPrint(() => { RegexIsMatchCompiledTest("dolor"); }, nameof(RegexIsMatchCompiledTest) + "-NoMatch");
TestAndPrint(() => { RegexIsMatchCompiledTest("engin"); }, nameof(RegexIsMatchCompiledTest) + "-Match");
}
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Test başlıyor!");
var scenarios = new TestScenarios();
scenarios.InvokeTests();
Console.WriteLine("Test tamamlandı!");
}
}
private void RegexIsMatchTest(string comparedTo)
{
for(var iLoop = 0; iLoop < this.TestIterationCount; iLoop++)
{
Regex.IsMatch(TestString, comparedTo);
}
}
private void RegexIsMatchCompiledTest(string comparedTo)
{
for(var iLoop = 0; iLoop < this.TestIterationCount; iLoop++)
{
Regex.IsMatch(TestString, comparedTo, RegexOptions.Compiled);
}
}
[Pure]
public bool Contains( string value ) {
return ( IndexOf(value, StringComparison.Ordinal) >=0 );
}
private void StringContainsTest(string comparedTo)
{
for(var iLoop = 0; iLoop < this.TestIterationCount; iLoop++)
{
TestString.Contains(comparedTo);
}
}
private void StringIndexOfTest(string comparedTo)
{
for(var iLoop = 0; iLoop < this.TestIterationCount; iLoop++)
{
TestString.IndexOf(comparedTo);
}
}
private void TestAndPrint(Action Test, string testName)
{
var watch = new Stopwatch();
GC.Collect(2, GCCollectionMode.Forced);
GC.WaitForFullGCComplete();
watch.Restart();
Test();
Console.WriteLine($"{testName} testi {watch.ElapsedMilliseconds / 10D} ms. sürdü");
}
private int TestIterationCount = 10_000_000;
private string TestString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur scelerisque libero eros, et efficitur mi laoreet ac";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment