- 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:
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.
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.
The HashSet.Contains check is not needed, just call Add method is fine because it has TryAdd semantics, — no key duplication exception.
There are multiple array allocations in OrderBy, avoidable.
ConvertAll will allocate a new list for every record, not needed.
ContainsKey is double hash container lookup anti-pattern.
Code rewritten: