Skip to content

Instantly share code, notes, and snippets.

@silashansen
Created June 7, 2021 13:02
Show Gist options
  • Save silashansen/f2f2dfb2fd4cda4eccfaed821c9a49f7 to your computer and use it in GitHub Desktop.
Save silashansen/f2f2dfb2fd4cda4eccfaed821c9a49f7 to your computer and use it in GitHub Desktop.
Benchmark IsEmptyString function
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MemoryTestSandbox
{
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<MemoryTests>();
}
}
[MemoryDiagnoser]
public class MemoryTests
{
[GlobalSetup]
public void Setup()
{
}
[Benchmark]
public int LambdaForm()
{
int count = 0;
count += LambdaFormImpl("\t");
count += LambdaFormImpl("");
count += LambdaFormImpl("hello world");
return count;
}
public int LambdaFormImpl(string statement)
{
bool result = string.IsNullOrWhiteSpace(statement) ||
statement.Any(x => !char.IsLetterOrDigit(x));
return result ? 1 : 0;
}
[Benchmark]
public int ExplicitForm()
{
int count = 0;
count += ExplicitFormImpl("\t");
count += ExplicitFormImpl("");
count += ExplicitFormImpl("hello world");
return count;
}
public int ExplicitFormImpl(string statement)
{
bool result = string.IsNullOrWhiteSpace(statement);
if (result == false)
{
for (int i = 0; i < statement.Length; i++)
{
bool valid = char.IsLetterOrDigit(statement[i]);
if (valid == true)
{
result = false;
break;
}
}
}
return result ? 1 : 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment