Created
July 31, 2017 03:39
-
-
Save davkean/dab5c068e3f907709f57a757a7e7fb3a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Attributes.Jobs; | |
using BenchmarkDotNet.Configs; | |
using BenchmarkDotNet.Jobs; | |
using Microsoft.VisualStudio.ProjectSystem; | |
using PathHelpers; | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Runtime.CompilerServices; | |
using System.Text; | |
using System.Threading.Tasks; | |
[LegacyJitX86Job, LegacyJitX64Job, RyuJitX64Job] | |
public class IndexOfAny | |
{ | |
public static char[] _array = new char[] { '\\', '/' }; | |
private const string ShortString = "This is a short string."; | |
private const string ShortStringEndingWithChar = "This is a short string./"; | |
[Params(ShortString, ShortStringEndingWithChar)] | |
public string Input { get; set; } | |
[Benchmark(Baseline = true)] | |
public void IndexOfAny_Baseline() | |
{ | |
for (int i = 0; i < 100000; i++) | |
{ | |
ContainsHelper.IndexOfAny(Input, _array); | |
} | |
} | |
[Benchmark] | |
public void IndexOfAny_HandWrittenLoop_HardcodedChars() | |
{ | |
for (int i = 0; i < 100000; i++) | |
{ | |
ContainsHelper.IndexOfAny_HandWrittenLoop_HardcodedChars(Input); | |
} | |
} | |
[Benchmark] | |
public void IndexOfAny_HandWrittenLoop() | |
{ | |
for (int i = 0; i < 100000; i++) | |
{ | |
ContainsHelper.IndexOfAny_HandWrittenLoop(Input, _array); | |
} | |
} | |
} | |
internal class ContainsHelper | |
{ | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
public static int IndexOfAny(string value, char[] array) | |
{ | |
return value.IndexOfAny(array); | |
} | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
public static int IndexOfAny_HandWrittenLoop_HardcodedChars(string value) | |
{ | |
for (int i = 0; i < value.Length; i++) | |
{ | |
char c = value[i]; | |
if (c == '/' || c == '\\') | |
{ | |
return i; | |
} | |
} | |
return -1; | |
} | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
public static int IndexOfAny_HandWrittenLoop(string value, char[] array) | |
{ | |
for (int i = 0; i < value.Length; i++) | |
{ | |
char c = value[i]; | |
foreach (var ch in array) | |
{ | |
if (c == ch) | |
return i; | |
} | |
} | |
return -1; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
BenchmarkDotNet.Running.BenchmarkRunner.Run<IndexOfAny>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment