Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EnsureCapacity should not have if (newCapacity < min) newCapacity = min; #176

Open
viveknuna opened this issue Sep 17, 2022 · 1 comment

Comments

@viveknuna
Copy link

I think if (newCapacity < min) newCapacity = min; should be removed, I have added items to the full capacity of the list but never hit breakpoint on line newCapacity = min;, Can someone tell the purpose of this line as well?

        private void EnsureCapacity(int min) {
            if (_items.Length < min) {
                int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
                // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
                // Note that this check works even when _items.Length overflowed thanks to the (uint) cast
                if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
                if (newCapacity < min) newCapacity = min;
                Capacity = newCapacity;
            }
        }
@svick
Copy link

svick commented Sep 17, 2022

Without that line, the array would grow, but it would not honor min. For example, if you have a list with Capacity = Length = 4 and AddRange a collection with 6 items, removing that line would grow the list to 8, when it needs to grow to 10.

Note that the equivalent .Net 7 source contains a comment explaining this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants