Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Created July 10, 2023 21:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JerryNixon/38fd05dd552dfea908245c0e67a7eafb to your computer and use it in GitHub Desktop.
Save JerryNixon/38fd05dd552dfea908245c0e67a7eafb to your computer and use it in GitHub Desktop.
Testing parameter types: IEnumerable<string> versus List<string>
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);
}
}
}
}
@JerryNixon
Copy link
Author

image

@ivandrofly
Copy link

ivandrofly commented Jul 10, 2023

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 allocation
is supposed to happen as it calls GetEnumerator() which will return a Enumerator and that Enumerator will then be casted
to 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?

@ivandrofly
Copy link

ivandrofly commented Jul 10, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment