runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Default ImmutableArray.ToBuilder capacity can cause expensive resize and copy right away

Open NinoFloris opened this issue 6 years ago • 9 comments

When creating a builder from a filled ImmutableArray it allocates the exact size of the original array, leaving no room to grow at all. I'd wager calling ToBuilder is mostly done to add elements (instead of remove/update) causing a resize + copy right away.

https://github.com/dotnet/runtime/blob/master/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Minimal.cs#L276

A workaround is to start from Empty and then change capacity yourself, though that still carries an extra alloc for the default 8 element array.

Related question would also be, what would be the downside of setting Array.Empty for the empty constructor until the first element is added? That would allow you to create a builder => change capacity => add, without extra allocs.

https://github.com/dotnet/runtime/blob/master/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs#L45-L46

NinoFloris avatar Dec 17 '19 23:12 NinoFloris

When creating a builder from a filled ImmutableArray it allocates the exact size of the original array, leaving no room to grow at all.

What would be the right number of additional elements to allocate in this case? Presumably, the performance benefits of using a builder only come when performing a nontrivial number of update operations, to justify the additional copying from immutable to builder and back. With that in mind, I don't think allocating a builder of size, say, length + 8 would have any meaningful performance impact?

eiriktsarpalis avatar May 27 '20 17:05 eiriktsarpalis

I usually use MoveToImmutable which is just a reference swap. You'd still have the copy into the Builder but for ImmutableArray I don't think you have any other option to Add to it that does any better than at least one full copy. It's not like a map or list in that regard so I'm not really sure what you mean by

Presumably, the performance benefits of using a builder only come when performing a nontrivial number of update operations,

If Builder just starts with some extra elements that would help, especially for small arrays (we use ImmutableArray almost everywhere, and there is talk of adding it to FSharp.Core too) anything beyond something like 8 elements (I'll leave that up to you) I'd expect downsides to outweigh returns.

You'd probably be regularly wasting space on empty array slots, and if you really need more then those are exactly the cases you are alluding to, large amounts of updates.

But again, we do regularly add a handful of elements to a small array, avoiding one or two resize copies in this case would be a nice and easy win.

NinoFloris avatar May 27 '20 23:05 NinoFloris

Fair enough. I suppose it would make sense since the current behaviour for nonempty arrays contradicts the comment above. I would welcome a change provided that it comes with a couple of benchmarks illustrating performance benefits. Would you be interested in contributing?

eiriktsarpalis avatar May 28 '20 13:05 eiriktsarpalis

Due to lack of recent activity, this issue has been marked as a candidate for backlog cleanup. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will undo this process.

This process is part of the experimental issue cleanup initiative we are currently trialing in a limited number of areas. Please share any feedback you might have in the linked issue.

ghost avatar Oct 26 '21 16:10 ghost

This issue will now be closed since it had been marked no recent activity but received no further activity in the past 14 days. It is still possible to reopen or comment on the issue, but please note that the issue will be locked if it remains inactive for another 30 days.

ghost avatar Nov 09 '21 18:11 ghost

Please keep it open msftbot

NinoFloris avatar Nov 09 '21 18:11 NinoFloris

I experimented with two approaches for the initial builder capacity: length + 8 length + min(8, length / 2) and compared both against the current behavior (length).

I benchmarked ToBuilder() followed by different numbers of Add() operations across different initial array sizes

Click to expand Benchmark Source Code
[MemoryDiagnoser]
    public class ToBuilderBenchmark
    {
        private ImmutableArray<int> _array;

        [Params(1, 2, 4, 8, 16, 32, 64)]
        public int Size { get; set; }

        [Params(1, 2, 4, 8, 16, 32, 64)]
        public int Adds { get; set; }

        [GlobalSetup]
        public void Setup()
        {
            var builder = ImmutableArray.CreateBuilder<int>();
            for (int i = 0; i < Size; i++)
            {
                builder.Add(i);
            }
            _array = builder.ToImmutable();
        }

        [Benchmark]
        public int Test()
        {
            var builder = _array.ToBuilder();

            for (int i = 0; i < Adds; i++)
            {
                builder.Add(i);
            }

            return builder.Count;
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            var config = DefaultConfig.Instance
                .AddJob(Job.Default.WithToolchain(InProcessEmitToolchain.Instance));

            BenchmarkRunner.Run<ToBuilderBenchmark>(config);
        }
    }

and this is representative results:

Size Adds Current (length) length + 8 length + min(8, length / 2)
1 1 34.01 ns 34.56 ns 35.26 ns
2 2 36.22 ns 36.32 ns 36.86 ns
4 4 44.84 ns 44.38 ns 43.20 ns
8 8 60.87 ns 60.29 ns 61.08 ns
16 16 96.61 ns 95.51 ns 97.51 ns
32 32 163.51 ns 163.25 ns 163.74 ns
64 64 293.24 ns 293.39 ns 296.68 ns
64 16 183.49 ns 178.52 ns 181.54 ns
64 32 215.43 ns 217.04 ns 218.69 ns
64 64 293.24 ns 293.39 ns 296.68 ns

In my opinion the results don't show a consistent performance improvement from either alternative. In addition, the allocation numbers are effectively unchanged across the approaches for the tested cases.

Given the lack of a consistent improvement, I don't see a strong performance justification for changing the current behavior.

aw0lid avatar Aug 29 '26 17:08 aw0lid

This is ultimately going to be dependent on the user and scenario; changing the default size is going to regress some and improve others.

If anything, I think this rather needs to be handled via some ToBuilder(int additionalCapacity) proposal that allows specifying how much additional space to allocate above/beyond this.Length

That cleanly solves the problem space without risking regression for existing callers and without causing an additional allocation/copy for devs that need initial additional capacity.

If we want to progress here, I'd recommend someone open an API proposal covering that and considering equivalents for the other ToBuilder APIs that the other collection types have.

tannergooding avatar Aug 29 '26 17:08 tannergooding

Sounds good! I agree that changing the default behavior risks regressions for existing callers, which is precisely what my benchmarks demonstrated. I like the idea of introducing a ToBuilder(int additionalCapacity) overload instead, and I will open an API proposal for this across the immutable collections.

aw0lid avatar Aug 29 '26 18:08 aw0lid