Skip to content

Instantly share code, notes, and snippets.

@trampster
Created December 2, 2020 09:10
Show Gist options
  • Save trampster/117692f09168f262a995b7bb95db29a9 to your computer and use it in GitHub Desktop.
Save trampster/117692f09168f262a995b7bb95db29a9 to your computer and use it in GitHub Desktop.
IsNumber benchmarks
using JsonSrcGen;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Text;
using System;
using System.Numerics;
using System.Runtime.InteropServices;
using JsonSrcGen.Runtime;
using System.Runtime.CompilerServices;
namespace Benchmarks
{
public class IsNumberBenchmark
{
string _input = "a1b2c3d4e5f6g7h8i9j0";
public IsNumberBenchmark()
{
}
static bool IsNumber(char character)
{
return character >= '0' && character <= '9';
}
[Benchmark]
public int IsNumberMethod()
{
int number = 0;
foreach(char value in _input)
{
if(IsNumber(value)) number++;
}
return number;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool IsNumberInline(char character)
{
return character >= '0' && character <= '9';
}
[Benchmark]
public int IsNumberInlineMethod()
{
int number = 0;
foreach(char value in _input)
{
if(IsNumberInline(value)) number++;
}
return number;
}
[Benchmark]
public int SwitchStatement()
{
int number = 0;
foreach(char value in _input)
{
switch(value)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
number++;
break;
}
}
return number;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment