In last week’s tips for using collections like
List<T>, we saw how struct types are sometimes boxed resulting in GC allocations. This week we’ll see how to avoid boxing and learn some of the clever tricks that .NET collection types use to make this possible.
Posts Tagged collection
Collection types like
Dictionary<TKey, TValue> are fundamental tools in C#. Sadly, I keep seeing the same misuses of them in codebase after codebase. Today we’ll look at the top 5 problems and learn how to easily avoid them!
We know that we should reduce the garbage our code produces to lighten the load on Unity’s garbage collector. The trouble is that many of the ways we’re creating garbage are hidden from us. One such way to inadvertently create a lot of garbage is to use a
foreach loop… at least that’s what we’ve been told. Do
foreach loops really create garbage for all types of arrays, lists, dictionaries, and the rest of the collections? Do they create garbage for every loop or just the first one? Today’s article investigates to put these questions to rest. Are you safe using
foreach loops or should you re-write everything to use
for. Read on to find out!
The first version of
SafeList tried to address a common problem: inserting and removing elements into a
List<T> while you loop over it. It had a lot of problems though and ended up being pretty much useless. Today’s article presents
SafeList 2.0, a radically-improved version that really solves the problem so you can actually use it as a drop-in replacement for
List<T>. Read on for the details, the source code, and even the unit tests that prove it handles all the nasty corner cases for you!