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

Reduce amount of heap allocations by changing List usage #365

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Marrow16180
Copy link
Contributor

In situations where the collection size is known, I've either changed how Lists are constructed to give them proper initial capacity or replaced them entirely by Arrays. I also removed some unneeded whitespace in one place and two unused variables in two other places.

@jackpoz
Copy link
Contributor

jackpoz commented Jun 29, 2019

how much does it change in C# between a List and an array both initialized with a known capacity and never resized ?

@Fabi
Copy link
Contributor

Fabi commented Jan 4, 2020

how much does it change in C# between a List and an array both initialized with a known capacity and never resized ?

In general you should always favor an array over a list whenever possible. That will always save memory usage and result in faster code.
For small loops you won't really notice a big difference but it will sum up after a while if the collections are saved. For temp collections you basically don't need to care unless you want some performance improvements

@HelloKitty
Copy link

HelloKitty commented Feb 13, 2020

@Fabi I disagree, List in C# is an abstraction over an array. It should be preferred while at the same time doing initial allocations that avoid reallocating due to add. Best of both worlds. List.Add implementation is almost always inlined meaning you're adding a bounds check around an array at most, and maybe even JIT could remove or optimize that in some cases.https://github.com/dotnet/runtime/blob/8593a477fb8f41029f9d7963658922b8d504c76e/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs#L198. I'm pretty sure the indexer can be inlined by JIT too.

Opting to use an array over a List is mostly some C/C++ style thinking in my opinion.

@jackpoz
Copy link
Contributor

jackpoz commented Feb 14, 2020

@HelloKitty that was exactly my point :) I think we should just make sure to specify the capacity in the List ctor

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

Successfully merging this pull request may close these issues.

4 participants