C# Performance/Memory Pitfalls

Some things you could look for in the code

  • Lists vs Queues: If you loop over a list the Garbage Collector cannot free memory even if you just need to process each object once. Use a Queue instead as soon as the object is removed and processed it can be garbage collected
  • MemoryStream: You shouldn’t construct MemoryStreams with the default constructor. This will result in a stream for 128 kb of data. Internally the data is saved in a byte array and as soon as you exceed the 128 kb if will allocated twice the old amount and it needs to copy the old content. If you know that you are writing about 64 mb of data you should therefore initialize the MemoryStream with that capacity. Otherwise it will need to expand itself 10 times. You will also end up with objects that are wasting space (32 mb, 16 mb, 8 mb, 4 mb, 2 mb, 1 mb, 512 kb, 256 kb, 128 kb). All these objects need to be garbage collected and if you are using MemoryStreams frequently you will generate big areas of non-continuous space and after a while C# will not be able to allocate big objects (arrays need continuous space!) anymore.
  • ArrayList: Quite the same as for MemoryStreams. Initialize them with a reasonable capacity

Where to optimize: Usually most of the time that a method takes is just in very few lines. A big refactoring is usually not worth the effort. Pay attention:

  • to use the right datastructure: p. x. never try to search elements in an unsorted list)
  • to use the right algorithm: BubbleSort is only efficient if the data is almost sorted
  • to use caching: if you need to access a calculated value a lot just save it in a member after you calculated it the first time but pay attention to invalidate the cache
  • to optimize the database access: do you really need distributed transactions?, use a connection pool, use one query to fetch all the data you need (and maybe a little bit more) instead of lots and lots of small queries

Leave a comment

Your email address will not be published. Required fields are marked *