Created
July 10, 2023 21:35
-
-
Save JerryNixon/38fd05dd552dfea908245c0e67a7eafb to your computer and use it in GitHub Desktop.
Testing parameter types: IEnumerable<string> versus List<string>
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
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Engines; | |
using BenchmarkDotNet.Running; | |
_ = BenchmarkRunner.Run<TestParamType>(); | |
[MemoryDiagnoser] | |
public class TestParamType | |
{ | |
private List<string> list = new(); | |
private Consumer consumer = new(); | |
[GlobalSetup] | |
public void Setup() | |
{ | |
list.AddRange(Enumerable.Range(1, 1_000_000).Select(x => Guid.NewGuid().ToString())); | |
} | |
[Benchmark(Baseline = true)] | |
public void Passing_IEnumerable() | |
{ | |
Test(list); | |
void Test(IEnumerable<string> list) | |
{ | |
foreach (var item in list) | |
{ | |
consumer.Consume(item); | |
} | |
} | |
} | |
[Benchmark] | |
public void Passing_List() | |
{ | |
Test(list); | |
void Test(List<string> list) | |
{ | |
foreach (var item in list) | |
{ | |
consumer.Consume(item); | |
} | |
} | |
} | |
} |
I think this can also help investigating the issue
https://stackoverflow.com/questions/3032750/structs-interfaces-and-boxing/3033357#3033357
https://stackoverflow.com/a/3032765/2766753 (Jon Skeet)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @JerryNixon thanks for you time to take a look into this.
I just take a look into .net 8's implementation for the
List<>
IEnumerable<T>.GetEnumerator()
and the allocationis supposed to happen as it calls
GetEnumerator()
which will return aEnumerator
and that Enumerator will then be castedto IEnumerable which is supposed to cause the boxing (for what I learn boxing happen whenever a value is type implicitly converted to
a Interface)
Ps: Maybe your Benchmark setup is missing something?