- Frugal Cafe
- Posts
- FC25: ICSharpCode.ILSpy.CSharpLanguage
FC25: ICSharpCode.ILSpy.CSharpLanguage
Magic of StringList replacing StringBuilder
I’m an active user of ILSpy to understand .Net implementations and search for their usages. So ILSpy is always open on my machine. Noticed it’s now running in .Net Core, I captured a trace and found this allocation stat:
StringBuilder accounts for 10% of total allocations, so there are StringBuilder usage issues. Here is the stack found:
CSharpLanguage.ToCSharpString is responsible for 33.5% of total allocations. Notice here we’ve an unusual call: StringBuilder.Insert. Source code:
This is a very unique pattern of using StringBuilder: all the calls are to StringBuilder.Insert(0, x). Let’s replace StringBuilder with the StringList class we created before (FC20: Need a List replacement? (beehiiv.com)):
StringBuilder.Insert(0, x) is now replaced by StringList.Add, StringBuilder.ToString is replaced with StringList.ReverseConcat. Implementation:
In best case where just a single name is needed without namespace, there is no not even a single allocation. The StringList is being reused here.
We should be able to remove most allocations here. Source code here: https://github.com/ProfFrugal/FrugalCafe/blob/master/Posts/CSharpLanguage.cs