Runtime: Proposal: Please add .ToLinkedList<T>()

Created on 9 Oct 2020  路  4Comments  路  Source: dotnet/runtime

Background and Motivation

When working with large amounts of data, .ToList() and .ToArray() can cause LOH fragmentation which results in a process using much more memory that necessary. Storing data in a node-based collection such as a LinkedList<T> alleviates this problem.

Proposed API

//
        // Summary:
        //     Creates a System.Collections.Generic.LinkedList`1 from an System.Collections.Generic.IEnumerable`1.
        //
        // Parameters:
        //   source:
        //     The System.Collections.Generic.IEnumerable`1 to create a System.Collections.Generic.LinkedList`1
        //     from.
        //
        // Type parameters:
        //   TSource:
        //     The type of the elements of source.
        //
        // Returns:
        //     A System.Collections.Generic.LinkedList`1 that contains elements from the input sequence.
        //
        // Exceptions:
        //   T:System.ArgumentNullException:
        //     source is null.
        public static LinkedList<TSource> ToLinkedList<TSource>(this IEnumerable<TSource> source) {
            return new LinkedList<TSource>(source);
        }

Usage Examples

var Data = MyEnumerable.ToLinkedList();

Alternative Designs

None

Risks

None

api-suggestion area-System.Collections

Most helpful comment

can cause LOH fragmentation which results in a process using much more memory that necessary.

LinkedList also consumes much more memory, because there's overhead for every node. There is also time overhead.

If you care about static fragmentation, you can require a LOH compact operation.

To achieve best performance, you'd better use a custom chunked list. LinkedList isn't a good solution at all.

All 4 comments

Tagging subscribers to this area: @eiriktsarpalis, @jeffhandley
See info in area-owners.md if you want to be subscribed.

can cause LOH fragmentation which results in a process using much more memory that necessary.

LinkedList also consumes much more memory, because there's overhead for every node. There is also time overhead.

If you care about static fragmentation, you can require a LOH compact operation.

To achieve best performance, you'd better use a custom chunked list. LinkedList isn't a good solution at all.

There are a few reasons why we shouldn't consider such an addition:

  • It may communicate that using a linked list representation is generally encouraged.
  • Having both ToArray() and ToLinkedList() methods might bring confusion as to which is preferable.
  • It is trivial to write a ToLinkedList() extension method, as already demonstrated in the OP.

I'm going to close this issue, but feel free to continue the conversation or reopen it.

Was this page helpful?
0 / 5 - 0 ratings