Skip to content

Instantly share code, notes, and snippets.

@darrenkopp
Last active December 23, 2017 02:16
Show Gist options
  • Save darrenkopp/7594ceee8b1cf6b9b3227de12fe8e7dc to your computer and use it in GitHub Desktop.
Save darrenkopp/7594ceee8b1cf6b9b3227de12fe8e7dc to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ConsoleApp3
{
class Program
{
static List<string> Words = SampleSet().ToList();
static readonly string[] KeywordArray = new string[] { "AS", "SELECT", "WHERE", "LOAD", "GROUP", "ORDER", "INCLUDE", "UPDATE" };
static readonly List<string> KeywordList = KeywordArray.ToList();
static readonly HashSet<string> KeywordSet = new HashSet<string>(KeywordArray, StringComparer.OrdinalIgnoreCase);
static void Main(string[] args)
{
(string, Action)[] benchmarks = new[]
{
("Fast Array", new Action(FastArray)),
("Set", new Action(SetCheck)),
("Normal Array", new Action(NormalArray)),
};
foreach (var benchmark in benchmarks)
RunBenchmark(benchmark);
Console.Read();
}
private static void RunBenchmark((string name, Action invoke) benchmark)
{
GC.Collect(3);
// warmup
for (var i = 0; i < 500; i++)
benchmark.invoke();
var timer = Stopwatch.StartNew();
for (var i = 0; i < 100000; i++)
benchmark.invoke();
timer.Stop();
Console.WriteLine($"{benchmark.name}: {timer.Elapsed}");
}
static void NormalArray()
{
foreach (var word in Words)
{
string alias = string.Empty;
if (KeywordList.Contains(word))
alias = "'" + word + "'";
}
}
static void FastArray()
{
foreach (var word in Words)
{
string alias = string.Empty;
foreach (var keyword in KeywordArray)
if (string.Equals(keyword, word))
{
alias = "'" + word + "'";
break;
}
}
}
static void SetCheck()
{
foreach (var word in Words)
{
string alias = string.Empty;
if (KeywordSet.Contains(word))
alias = "'" + word + "'";
}
}
private static IEnumerable<string> SampleSet()
{
var random = new Random();
var buffer = new StringBuilder(8);
return Enumerable.Range(0, 1000)
.Select(x => random.Next(2, 7))
.Select(x => CreateString(x, buffer, random));
}
static string CreateString(int length, StringBuilder buffer, Random random)
{
buffer.Clear();
for (var i = 0; i < length; i++)
buffer.Append(random.Next((char)random.Next(65, 90)));
return buffer.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment