Created
June 7, 2021 13:02
-
-
Save silashansen/f2f2dfb2fd4cda4eccfaed821c9a49f7 to your computer and use it in GitHub Desktop.
Benchmark IsEmptyString function
This file contains 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.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