Skip to content

Instantly share code, notes, and snippets.

@EamonNerbonne
Last active October 14, 2019 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EamonNerbonne/51a520e2a04806d34d4c38d1362857c5 to your computer and use it in GitHub Desktop.
Save EamonNerbonne/51a520e2a04806d34d4c38d1362857c5 to your computer and use it in GitHub Desktop.
//timings "on my machine", fixed clockspeed, multiple runs have stable timings with less than 1% variation, x64 .net core 3.0 roslyn 3.3.1-beta4 via linqpad 6.3.0 beta.
//obviously there's some noise, but even the timing differences between 0.66 and 0.68 appear to be reproducible on this machine; not just random happenstance
var arr = Enumerable.Range(1, 10_000).Select(i => i % 2 == 0 ? default(int?) : i).ToArray();
var filteredSeq = arr.Where(o=>o!=null);
var sw = Stopwatch.StartNew();
var sum =0l;
for (int iter = 0; iter < 100_000; iter++)
{
#if false
foreach (var val in arr)
{
//empty loop: 0.2s
//sum += val.HasValue ? val.GetValueOrDefault() : 0; //0.81s
sum += val ?? 0; //0.45s
//sum += val.HasValue ? val.Value : 0;//0.66s
//sum += val.GetValueOrDefault(); //0.45s
//sum += val.HasValue ? val.GetValueOrDefault() : 1; //0.68s
//sum += val ?? 1; //0.68s
//sum += val.HasValue ? val.Value : 1;//0.66s
}
#elif false
for (int idx = 0; idx < arr.Length; idx++)
{
//empty loop: 0.2s
//sum += arr[idx].HasValue ? arr[idx].GetValueOrDefault() : 0; //0.81s
//sum += arr[idx] ?? 0; //0.45s
//sum += arr[idx].HasValue ? arr[idx].Value : 0; 0.66s
//sum += arr[idx].GetValueOrDefault(); 0.45s
}
#else
foreach (var val in filteredSeq)
{
//empty loop: 0.2s
//sum += val.HasValue ? val.GetValueOrDefault() : 0; //7.2s
//sum += val ?? 0; //7.1s
//sum += val.HasValue ? val.Value : 0;//7.2s
sum += val.GetValueOrDefault(); //7.1s
}
#endif
}
sw.Elapsed.TotalSeconds.Dump();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment