Created
July 9, 2023 13:45
-
-
Save bellons91/876d5707cd9b9e768866c45e8f5d155d to your computer and use it in GitHub Desktop.
IsNullOrEmpty vs IsNullOrWhitespace
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
#LINQPad optimize+ | |
void Main() | |
{ | |
var summary = BenchmarkRunner.Run<StringNullOrEmptyPerformance>(); | |
} | |
[MemoryDiagnoser] | |
public class StringNullOrEmptyPerformance | |
{ | |
private List<string> items; | |
[Params(2, 100, 1000)] | |
public int Lenght; | |
[GlobalSetup] | |
public void GlobalSetup() | |
{ | |
string[] values = new string[] {"", string.Empty, " ", "/n", null}; | |
Random rd = new Random(); | |
items = Enumerable.Range(0, Lenght) | |
.Select(e => values.ElementAt( rd.Next(0, values.Length))) | |
.ToList(); | |
} | |
[Benchmark] | |
public void UsingIsNullOrEmpty() | |
{ | |
for (int i = 0; i < items.Count; i++) | |
{ | |
_ = string.IsNullOrEmpty( items[i]); | |
} | |
} | |
[Benchmark] | |
public void UsingIsNullOrWhitespace() | |
{ | |
for (int i = 0; i < items.Count; i++) | |
{ | |
_ = string.IsNullOrWhiteSpace(items[i]); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment