Skip to content

Instantly share code, notes, and snippets.

@stimms
Created May 26, 2018 19:28
Show Gist options
  • Save stimms/2cf02f1d0f577d1e1325c63067727ef0 to your computer and use it in GitHub Desktop.
Save stimms/2cf02f1d0f577d1e1325c63067727ef0 to your computer and use it in GitHub Desktop.
Benchmark of list null checking
using System;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Attributes.Columns;
using BenchmarkDotNet.Attributes.Exporters;
using BenchmarkDotNet.Attributes.Jobs;
using BenchmarkDotNet.Running;
namespace benchmark
{
[CoreJob]
[RPlotExporter, RankColumn]
public class ListNullCheck
{
private List<string> toCheck = null;
[Benchmark]
public void Traditional(){
if(toCheck!=null)
{
foreach (var item in toCheck)
{
}
}
}
[Benchmark]
public void Inline(){
foreach(var item in toCheck ?? new List<string>())
{
}
}
}
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<ListNullCheck>();
}
}
}
BenchmarkDotNet=v0.10.14, OS=Windows 10.0.16299.431 (1709/FallCreatorsUpdate/Redstone3)
Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
Frequency=2742186 Hz, Resolution=364.6726 ns, Timer=TSC
.NET Core SDK=2.1.300-rc1-008673
[Host] : .NET Core 2.1.0-rc1 (CoreCLR 4.6.26426.02, CoreFX 4.6.26426.04), 64bit RyuJIT
Core : .NET Core 2.1.0-rc1 (CoreCLR 4.6.26426.02, CoreFX 4.6.26426.04), 64bit RyuJIT
Job=Core Runtime=Core
Method | Mean | Error | StdDev | Rank |
------------ |---------:|----------:|----------:|-----:|
Traditional | 10.48 ns | 0.1587 ns | 0.1484 ns | 1 |
Inline | 18.58 ns | 0.4107 ns | 0.5194 ns | 2 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment