Created
July 9, 2023 13:46
-
-
Save bellons91/ced7d6c07f127ed992efa960ea1503d9 to your computer and use it in GitHub Desktop.
IsNullOrEmpty and Trim 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<StringEmptyTrimPerformance>(); | |
} | |
[MemoryDiagnoser] | |
public class StringEmptyTrimPerformance | |
{ | |
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 UsingIsNullOrEmptyAndTrim() | |
{ | |
for (int i = 0; i < items.Count; i++) | |
{ | |
_ = string.IsNullOrEmpty( items[i]?.Trim()); | |
} | |
} | |
[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