Criteo R&D Blog
Published in

Criteo R&D Blog

Photo by Clark Van Der Beken on Unsplash

Memory Anti-Patterns in C#

Finalizer and IDisposable usage

  • after it is allocated, a reference is kept in a Finalization internal queue
  • after a collection, if it is no more referenced, this reference is moved into another fReachable internal queue and treated as a root until a dedicated thread calls its finalizer code
  • native resources (i.e. IntPtr fields) must always be cleaned up
  • managed resources (i.e. IDisposable fields) should be disposed when called from Dispose (not from GC)
  • it is only meaningful when called from Dispose (not from GC) to avoid extending its lifetime.
  • it means that the finalizer will never be called. If it were, it would have called Cleanup that would have returned immediately because _disposed is true.

Provide list capacity when possible

  1. A new array is allocated
  2. The former values are copied to the new array
  3. The former array is no more referenced

Prefer StringBuilder to +/+= for string concatenation

Caching strings and interning

Don’t (re)create objects

Best practices with LINQ

Prefer IEnumerable<T> to IList<T>

FirstOrDefault and Any are your friends… but might not be needed

Avoid unnecessary ToList()/ToArray() calls

  1. optimization sake to avoid executing the underlying query several times when it is expensive
  2. removing/adding elements from a sequence
  3. storing the result of a query execution in a class field

Prefer IEnumerable<>.Any to List<>.Exists

Prefer Any to Count when checking for emptiness

Order in extension methods might matter

IsEven(1)
IsEven(2)
IsMultipleOf3(2)
IsEven(3)
IsEven(4)
IsMultipleOf3(4)
IsEven(5)
IsEven(6)
IsMultipleOf3(6)
--> 6
--------------------------------
IsEven(1)
IsEven(2)
IsMultipleOf3(2)
IsEven(3)
IsEven(4)
IsMultipleOf3(4)
IsEven(5)
IsEven(6)
IsMultipleOf3(6)
--> 6

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store