Does C# 6 string interpolation use boxing like string.Format() does for its arguments?
Asked Answered
L

1

7

I am asking this for performance sake - using lots of boxing makes lots of heap allocations which brings more GC collects which sometimes causes apps to freeze for a glimpse which annoy users.

Locker answered 19/10, 2016 at 14:8 Comment(1)
According to this related post, string interpolation is translated to string.Format() at compile-time. See also here.Baty
L
7

All string interpolation does (at least in the common case) is to call string.Format().

Right now, calling string.Format() allocates quite a lot and not just due to boxing (for example, string.Format("{0:s} - {1:B}: The value is: {2:C2}", DateTime.UtcNow, Guid.NewGuid(), 3.50m) makes 13 allocations, only 3 of those due to boxing), though there is talk about improving that in the future.

Though as usual when it comes to performance, you generally should not just blindly write unreadable code everywhere because the readable version has known performance issues. Instead, limit the unreadable efficient code to the parts of your code that actually need it.

Lovash answered 19/10, 2016 at 15:30 Comment(2)
"has known performance issues." - is it even a performance issue in the first place? The current String.Format system was designed back in 2000-2001 when computing resources were a fraction of what they are today and I don't recall hearing anyone having a problem with it back then - why are people making a fuss now?Methinks
@Methinks It is a performance issue. Whether that issue is relevant to you depends on a lot of factors. And if it's not relevant to you, you should just ignore it.Lovash

© 2022 - 2024 — McMap. All rights reserved.