Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

71%
+3 −0
Q&A Do Where and OfType preserve List capacity?

TL;DR: for .Where<T>(), no, for .Cast<T>(), yes. At least, when possible, when the prior operator in the chain passes count info along. Looking at the implementation of .ToList(), we...

posted 1y ago by JakenVeina‭  ·  edited 1y ago by JakenVeina‭

Answer
#3: Post edited by user avatar JakenVeina‭ · 2025-07-26T05:15:18Z (about 1 year ago)
  • TL;DR: for `.Where<T>()`, no, for `.Cast<T>()`, yes. At least, when possible, when the prior operator in the chain passes count info along.
  • ---
  • Looking at [the implementation of `.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/ToCollection.cs#L58), we can see how its optimizations work.
  • ```cs
  • public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
  • {
  • if (source is null)
  • {
  • ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
  • }
  • if (!IsSizeOptimized && source is Iterator<TSource> iterator)
  • {
  • return iterator.ToList();
  • }
  • return new List<TSource>(source);
  • }
  • ```
  • There's some optimizations within the `List<T>` constructor for initializing the capacity when `source` is an `ICollection<T>`, but the real optimizations within LINQ are built around that `Iterator<T>` type we're checking for. It's an `abstract` class with it's own `ToList()` implementation, as we can see, which different operators can subclass and override.
  • For example, we can see the optimization in play within [`ArraySelectIterator<T>.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Select.SpeedOpt.cs#L153C1-L162C14), which is what [`.Select<T>()` returns when its input is a `List<T>`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Select.cs#L52):
  • ```cs
  • public override List<TResult> ToList()
  • {
  • TSource[] source = _source;
  • Debug.Assert(source.Length > 0);
  • var results = new List<TResult>(source.Length);
  • Fill(source, SetCountAndGetSpan(results, source.Length), _selector);
  • return results;
  • }
  • ```
  • The operator not only constructs the new `List<T>` with an initial capacity to match the source array, but also bypasses normal safety checks to populate it, with that internal `Fill()` helper method. The implementation for `ListSelectIterator<T>.ToList()` looks basically identical.
  • ---
  • Now, looking at [`.ArrayWhereIterator<T>.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Where.SpeedOpt.cs#L217), we can see there's no capacity such optimizations:
  • ```cs
  • public override List<TSource> ToList() => ToList(_source, _predicate);
  • public static List<TSource> ToList(ReadOnlySpan<TSource> source, Func<TSource, bool> predicate)
  • {
  • SegmentedArrayBuilder<TSource>.ScratchBuffer scratch = default;
  • SegmentedArrayBuilder<TSource> builder = new(scratch);
  • foreach (TSource item in source)
  • {
  • if (predicate(item))
  • {
  • builder.Add(item);
  • }
  • }
  • List<TSource> result = builder.ToList();
  • builder.Dispose();
  • return result;
  • }
  • ```
  • And this makes sense. We don't know how any items are actually going to pass the predicate, until after we evaluate them all, so we can't *really* know how much space we need to pre-allocate. Better to not over-allocate, and let the consumer do their own optimization, if that's important to them.
  • ---
  • We can do the same inspection for `.Cast<T>()` and see that it all looks mostly the same as `.Select<T>()`. Which also makes sense, since it functionally IS just a `.Select<T>()`.
  • TL;DR: for `.Where<T>()`, no, for `.Cast<T>()`, yes. At least, when possible, when the prior operator in the chain passes count info along.
  • ---
  • Looking at [the implementation of `.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/ToCollection.cs#L58), we can see how its optimizations work.
  • ```cs
  • public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
  • {
  • if (source is null)
  • {
  • ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
  • }
  • if (!IsSizeOptimized && source is Iterator<TSource> iterator)
  • {
  • return iterator.ToList();
  • }
  • return new List<TSource>(source);
  • }
  • ```
  • There's some optimizations within the `List<T>` constructor for initializing the capacity when `source` is an `ICollection<T>`, but the real optimizations within LINQ are built around that `Iterator<T>` type we're checking for. It's an `abstract` class with it's own `ToList()` implementation, as we can see, which different operators can subclass and override.
  • For example, we can see the optimization in play within [`ArraySelectIterator<T>.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Select.SpeedOpt.cs#L153C1-L162C14), which is what [`.Select<T>()` returns when its input is a `List<T>`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Select.cs#L52):
  • ```cs
  • public override List<TResult> ToList()
  • {
  • TSource[] source = _source;
  • Debug.Assert(source.Length > 0);
  • var results = new List<TResult>(source.Length);
  • Fill(source, SetCountAndGetSpan(results, source.Length), _selector);
  • return results;
  • }
  • ```
  • The operator not only constructs the new `List<T>` with an initial capacity to match the source array, but also bypasses normal safety checks to populate it, with that internal `Fill()` helper method. The implementation for `ListSelectIterator<T>.ToList()` looks basically identical.
  • ---
  • Now, looking at [`.ArrayWhereIterator<T>.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Where.SpeedOpt.cs#L217), we can see there's no such capacity optimizations:
  • ```cs
  • public override List<TSource> ToList() => ToList(_source, _predicate);
  • public static List<TSource> ToList(ReadOnlySpan<TSource> source, Func<TSource, bool> predicate)
  • {
  • SegmentedArrayBuilder<TSource>.ScratchBuffer scratch = default;
  • SegmentedArrayBuilder<TSource> builder = new(scratch);
  • foreach (TSource item in source)
  • {
  • if (predicate(item))
  • {
  • builder.Add(item);
  • }
  • }
  • List<TSource> result = builder.ToList();
  • builder.Dispose();
  • return result;
  • }
  • ```
  • And this makes sense. We don't know how many items are actually going to pass the predicate, until after we evaluate them all, so we can't *really* know how much space we need to pre-allocate. Better to not over-allocate, and let the consumer do their own optimization, if that's important to them.
  • ---
  • We can do the same inspection for `.Cast<T>()` and see that it all looks mostly the same as `.Select<T>()`. Which also makes sense, since it functionally IS just a `.Select<T>()`.
#2: Post edited by user avatar JakenVeina‭ · 2025-07-11T04:10:06Z (about 1 year ago)
  • TL;DR: for `.Where<T>()`, no, for `.Cast<T>()`, yes. At least, when possible.
  • ---
  • Looking at [the implementation of `.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/ToCollection.cs#L58), we can see how its optimizations work.
  • ```cs
  • public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
  • {
  • if (source is null)
  • {
  • ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
  • }
  • if (!IsSizeOptimized && source is Iterator<TSource> iterator)
  • {
  • return iterator.ToList();
  • }
  • return new List<TSource>(source);
  • }
  • ```
  • There's some optimizations within the `List<T>` constructor for initializing the capacity when `source` is an `ICollection<T>`, but the real optimizations within LINQ are built around that `Iterator<T>` type we're checking for. It's an `abstract` class with it's own `ToList()` implementation, as we can see, which different operators can subclass and override.
  • For example, we can see the optimization in play within [`ArraySelectIterator<T>.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Select.SpeedOpt.cs#L153C1-L162C14), which is what [`.Select<T>()` returns when its input is a `List<T>`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Select.cs#L52):
  • ```cs
  • public override List<TResult> ToList()
  • {
  • TSource[] source = _source;
  • Debug.Assert(source.Length > 0);
  • var results = new List<TResult>(source.Length);
  • Fill(source, SetCountAndGetSpan(results, source.Length), _selector);
  • return results;
  • }
  • ```
  • The operator not only constructs the new `List<T>` with an initial capacity to match the source array, but also bypasses normal safety checks to populate it, with that internal `Fill()` helper method. The implementation for `ListSelectIterator<T>.ToList()` looks basically identical.
  • ---
  • Now, looking at [`.ArrayWhereIterator<T>.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Where.SpeedOpt.cs#L217), we can see there's no capacity such optimizations:
  • ```cs
  • public override List<TSource> ToList() => ToList(_source, _predicate);
  • public static List<TSource> ToList(ReadOnlySpan<TSource> source, Func<TSource, bool> predicate)
  • {
  • SegmentedArrayBuilder<TSource>.ScratchBuffer scratch = default;
  • SegmentedArrayBuilder<TSource> builder = new(scratch);
  • foreach (TSource item in source)
  • {
  • if (predicate(item))
  • {
  • builder.Add(item);
  • }
  • }
  • List<TSource> result = builder.ToList();
  • builder.Dispose();
  • return result;
  • }
  • ```
  • And this makes sense. We don't know how any items are actually going to pass the predicate, until after we evaluate them all, so we can't *really* know how much space we need to pre-allocate. Better to not over-allocate, and let the consumer do their own optimization, if that's important to them.
  • ---
  • We can do the same inspection for `.Cast<T>()` and see that it all looks mostly the same as `.Select<T>()`. Which also makes sense, since it functionally IS just a `.Select<T>()`.
  • TL;DR: for `.Where<T>()`, no, for `.Cast<T>()`, yes. At least, when possible, when the prior operator in the chain passes count info along.
  • ---
  • Looking at [the implementation of `.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/ToCollection.cs#L58), we can see how its optimizations work.
  • ```cs
  • public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
  • {
  • if (source is null)
  • {
  • ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
  • }
  • if (!IsSizeOptimized && source is Iterator<TSource> iterator)
  • {
  • return iterator.ToList();
  • }
  • return new List<TSource>(source);
  • }
  • ```
  • There's some optimizations within the `List<T>` constructor for initializing the capacity when `source` is an `ICollection<T>`, but the real optimizations within LINQ are built around that `Iterator<T>` type we're checking for. It's an `abstract` class with it's own `ToList()` implementation, as we can see, which different operators can subclass and override.
  • For example, we can see the optimization in play within [`ArraySelectIterator<T>.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Select.SpeedOpt.cs#L153C1-L162C14), which is what [`.Select<T>()` returns when its input is a `List<T>`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Select.cs#L52):
  • ```cs
  • public override List<TResult> ToList()
  • {
  • TSource[] source = _source;
  • Debug.Assert(source.Length > 0);
  • var results = new List<TResult>(source.Length);
  • Fill(source, SetCountAndGetSpan(results, source.Length), _selector);
  • return results;
  • }
  • ```
  • The operator not only constructs the new `List<T>` with an initial capacity to match the source array, but also bypasses normal safety checks to populate it, with that internal `Fill()` helper method. The implementation for `ListSelectIterator<T>.ToList()` looks basically identical.
  • ---
  • Now, looking at [`.ArrayWhereIterator<T>.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Where.SpeedOpt.cs#L217), we can see there's no capacity such optimizations:
  • ```cs
  • public override List<TSource> ToList() => ToList(_source, _predicate);
  • public static List<TSource> ToList(ReadOnlySpan<TSource> source, Func<TSource, bool> predicate)
  • {
  • SegmentedArrayBuilder<TSource>.ScratchBuffer scratch = default;
  • SegmentedArrayBuilder<TSource> builder = new(scratch);
  • foreach (TSource item in source)
  • {
  • if (predicate(item))
  • {
  • builder.Add(item);
  • }
  • }
  • List<TSource> result = builder.ToList();
  • builder.Dispose();
  • return result;
  • }
  • ```
  • And this makes sense. We don't know how any items are actually going to pass the predicate, until after we evaluate them all, so we can't *really* know how much space we need to pre-allocate. Better to not over-allocate, and let the consumer do their own optimization, if that's important to them.
  • ---
  • We can do the same inspection for `.Cast<T>()` and see that it all looks mostly the same as `.Select<T>()`. Which also makes sense, since it functionally IS just a `.Select<T>()`.
#1: Initial revision by user avatar JakenVeina‭ · 2025-07-11T04:09:15Z (about 1 year ago)
TL;DR: for `.Where<T>()`, no, for `.Cast<T>()`, yes. At least, when possible.

---

Looking at [the implementation of `.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/ToCollection.cs#L58), we can see how its optimizations work.

```cs
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
    if (source is null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
    }

    if (!IsSizeOptimized && source is Iterator<TSource> iterator)
    {
        return iterator.ToList();
    }

    return new List<TSource>(source);
}
```

There's some optimizations within the `List<T>` constructor for initializing the capacity when `source` is an `ICollection<T>`, but the real optimizations within LINQ are built around that `Iterator<T>` type we're checking for. It's an `abstract` class with it's own `ToList()` implementation, as we can see, which different operators can subclass and override.

For example, we can see the optimization in play within [`ArraySelectIterator<T>.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Select.SpeedOpt.cs#L153C1-L162C14), which is what [`.Select<T>()` returns when its input is a `List<T>`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Select.cs#L52):

```cs
public override List<TResult> ToList()
{
    TSource[] source = _source;
    Debug.Assert(source.Length > 0);

    var results = new List<TResult>(source.Length);
    Fill(source, SetCountAndGetSpan(results, source.Length), _selector);

    return results;
}
```

The operator not only constructs the new `List<T>` with an initial capacity to match the source array, but also bypasses normal safety checks to populate it, with that internal `Fill()` helper method. The implementation for `ListSelectIterator<T>.ToList()` looks basically identical.

---

Now, looking at [`.ArrayWhereIterator<T>.ToList()`](https://github.com/dotnet/runtime/blob/1df4e5231ea9ce2efac8dbc0eaede7cd4a928324/src/libraries/System.Linq/src/System/Linq/Where.SpeedOpt.cs#L217), we can see there's no capacity such optimizations:

```cs
public override List<TSource> ToList() => ToList(_source, _predicate);

public static List<TSource> ToList(ReadOnlySpan<TSource> source, Func<TSource, bool> predicate)
{
    SegmentedArrayBuilder<TSource>.ScratchBuffer scratch = default;
    SegmentedArrayBuilder<TSource> builder = new(scratch);

    foreach (TSource item in source)
    {
        if (predicate(item))
        {
            builder.Add(item);
        }
    }

    List<TSource> result = builder.ToList();
    builder.Dispose();

    return result;
}
```

And this makes sense. We don't know how any items are actually going to pass the predicate, until after we evaluate them all, so we can't *really* know how much space we need to pre-allocate. Better to not over-allocate, and let the consumer do their own optimization, if that's important to them.

---

We can do the same inspection for `.Cast<T>()` and see that it all looks mostly the same as `.Select<T>()`. Which also makes sense, since it functionally IS just a `.Select<T>()`.