What if you already have a collection in memory, like after calling a service or database, and you need to return it as a different collection type? Here are two examples.
return new ObservableCollection<T>(collection);
or
var collection = this.people.ToHashSet();
Benchmark Results
Below are the benchmark results for various ways to return a collection. These results are for your information. As I have said already, remember to perform benchmarking on your types.
Allocations
- ToArray() = 104 – 20,024 bytes
- ToCollection() = 424 – 65,989 bytes
- ToHashSet() = 376 – 56,117 bytes
- ToObservableCollection() = 192 – 20,112 bytes
- ToReadOnlyCollection() = 24 bytes
Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
DonateDonate monthlyDonate yearlyIf you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave
© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.
OF course changing the output type changes the performance…. More interesting is looking to see if the means of changing has an impact…. stuff.ToList() vs new List(stuff)…. Then go for something completely different and use struct rather than class types [and the new nullable reference types – that are not nullable]….