- Frugal Cafe
- Posts
- FC69: Writing integer attribute to XmlWriter without allocation
FC69: Writing integer attribute to XmlWriter without allocation
Here is another expensive allocation stack found in PerfView’s XML generation code path:
XmlStackSourceWriter.WriteStacks is responsible for 33.5% of total allocations, mostly due to integer to string conversions. Here is the source code:
The code is writing out three integers in a loop, all converted to strings first.
The problem is with the design of XmlWriter, it only allows writing out string attribute values. But if you can break the call into pieces, we can find a way to achieve zero-allocation integer attribute output:
We’re adding a wrapper class XmlWriterExt which has a 23 character buffer inside. To write out an integer attribute, we split the call into three steps: WriteStartAttribute, write value, and then WriteEndAttribute. To write out the value, we convert the integer into character form in the char buffer, then call XmlWriter.WriteChars.
We’re just adding two heap allocations. But there are big loops in XML generation, so they do not even count.
Original code can be changed to: