Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bellons91/ced7d6c07f127ed992efa960ea1503d9 to your computer and use it in GitHub Desktop.
Save bellons91/ced7d6c07f127ed992efa960ea1503d9 to your computer and use it in GitHub Desktop.
IsNullOrEmpty and Trim vs IsNullOrWhitespace
#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