Created
August 16, 2020 20:25
-
-
Save badamczewski/e3c87f4de0e7a23e7b7d22c5ea473ef5 to your computer and use it in GitHub Desktop.
LinqLast Performance
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
| Method | Mean | Error | StdDev | Ratio | | |
|----------- |-----------:|----------:|----------:|------:| | |
| Linq | 16.8220 ns | 0.4014 ns | 1.1582 ns | 1.00 | | |
| Last | 0.9100 ns | 0.0678 ns | 0.1797 ns | 0.06 | | |
| LastBetter | 0.8448 ns | 0.0645 ns | 0.1482 ns | 0.05 | | |
Code: | |
public class Benchmark | |
{ | |
private List<int> list; | |
[GlobalSetup] | |
public void Global() | |
{ | |
list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; | |
} | |
[Benchmark(Baseline = true)] | |
public int Linq() | |
{ | |
return list.Last(); | |
} | |
[Benchmark] | |
public int Last() | |
{ | |
if (list == null) throw new ArgumentNullException(); | |
if (list.Count > 0) | |
return list[list.Count - 1]; | |
throw new ArgumentException(); | |
} | |
[Benchmark] | |
public int LastBetter() | |
{ | |
var idx = list.Count; | |
if (list == null || idx == 0) throw new ArgumentNullException(); | |
return list[idx - 1]; | |
throw new ArgumentException(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment