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
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...
#3: Post edited
- 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
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
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>()`.
