0

Collection Performance: Converting A List To Different Collection Types – dotNet...

 2 years ago
source link: https://dotnettips.wordpress.com/2021/10/21/collection-performance-converting-a-list-to-different-types/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Collection Performance: Converting A List To Different Collection Types

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?

public Person[] GetPeopleAsArray()
{
   return people.ToArray();
}

public LinkedList<Person> GetPeopleAsLinkedList()
{
   return new LinkedList<Person>(people);
}

In the example above, the people variable is typed as List<Person>(), which you can see for yourself in the code I used to run the benchmarks, that is available online.

Benchmark Results

Below are the benchmark results for various ways to return a collection from a List<>. These results are for your own information. As I have said already, remember to perform benchmarking on your own types.

CONVERTING LIST-CHART

CONVERTING LIST TO READ ONLY COLLECTION-CHART

CONVERTING LIST TO IMMUTABLE COLLECTION-CHART

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

Tagged Code Performance

I live in San Diego, Ca USA View all posts by dotNetDave


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK