Search code examples
c#heap-memorycil

ToString() creates an object on the heap?


num.ToString() Will create an object on the heap during the execution of WriteLine()?

int num = 83424;
Console.WriteLine(num.ToString());

Solution

  • Almost certainly, yes. There may be some behind-the-scenes tricks to avoid allocations for some small integers, zero, etc (a quick test in .NET 6 and .NET 7 suggests this is the case for 0-9 inclusive).

    If that isn't desirable, there are ways of avoiding it - for example Utf8Formatter has methods to write primitives to a span, typically some reusable buffer memory - but this has a different API and usage than ToString().