WowPacketParser icon indicating copy to clipboard operation
WowPacketParser copied to clipboard

Reduce amount of heap allocations by changing List usage

Open Marrow16180 opened this issue 6 years ago • 4 comments

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.

Marrow16180 avatar Jun 25 '18 19:06 Marrow16180

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

jackpoz avatar Jun 29 '19 11:06 jackpoz

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

Fabi avatar Jan 04 '20 13:01 Fabi

@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 avatar Feb 13 '20 19:02 HelloKitty

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

jackpoz avatar Feb 14 '20 06:02 jackpoz