Reduce amount of heap allocations by changing List usage#365
Reduce amount of heap allocations by changing List usage#365Marrow16180 wants to merge 1 commit intoTrinityCore:masterfrom
Conversation
…placing them by Array
|
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. |
|
@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. |
|
@HelloKitty that was exactly my point :) I think we should just make sure to specify the capacity in the List ctor |
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.