Skip to content

The spread operator is significantly slower than using the special constructor when converting data to ObservableCollection #113788

@HotCakeX

Description

@HotCakeX

Take this benchmark for example

public class ObservableCollectionBenchmark<T>
{
    private List<T> Data;

    [GlobalSetup]
    public void Setup()
    {
        Data = Enumerable.Range(0, 10000).Select(i => (T)Convert.ChangeType(i, typeof(T))).ToList();
    }

    [Benchmark]
    public void CollectionExpression()
    {
        ObservableCollection<T> Result = [];
        Result = [.. Data];
    }

    [Benchmark]
    public void ConstructorInitialization()
    {
        ObservableCollection<T> Result = [];
        Result = new ObservableCollection<T>(Data);
    }

    public static void Run()
    {
        var summary = BenchmarkRunner.Run<ObservableCollectionBenchmark<int>>();
    }
}

class Program
{
    static void Main()
    {
        ObservableCollectionBenchmark<int>.Run();
    }
}

When I run it, i get the following result

Image


As you can see, using [.. ] is a lot slower than using this: https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1.-ctor

Processor = Intel 14th gen Core i7

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions