• Frugal Cafe
  • Posts
  • FC64: Sometimes you need to rewrite the whole method.

FC64: Sometimes you need to rewrite the whole method.

Performance issues are never alone

Performance issues are never alone. Once you found one, you can find a bunch of them nearby. Somethings you may need to rewrite the whole method. Here is a upper level method in ServiceStack.Text CSV generation:

Here are the potential issues:

  1. The code is storing data into a new list, apparently to avoid double evaluations of LINQ expression. This is normally okay, except when the record count is over 8K. The list could land in LOH, causing memory/garbage collection issues.

  2. The code is walking every dictionary key collection using Keys property getter. This will cause key collection to be allocated and held by every dictionary.

  3. The HashSet.Contains check is not needed, just call Add method is fine because it has TryAdd semantics, — no key duplication exception.

  4. There are multiple array allocations in OrderBy, avoidable.

  5. ConvertAll will allocate a new list for every record, not needed.

  6. ContainsKey is double hash container lookup anti-pattern.

Code rewritten: