How can I test the differences in scenarios of using interpolated strings vs concatenating strings such as this example:
String interpolation
const string a = "I change per class or method";
string b = $"abcdefghijklmnopqrstuvw {a} xyz";
Console.WriteLine(b);
IL_0000: ldstr "abcdefghijklmnopqrstuvw {0} xyz"
IL_0005: ldstr "I change per class or method"
IL_000A: call System.String.Format
IL_000F: call System.Console.WriteLine
IL_0014: ret
This will hopefully store a single value of a
via string interning for all of the code but the cost of using string.Format
may cancel out benefits of storing a single, small string.
Concatenation
const string a = "I change per class or method";
string b = "abcdefghijklmnopqrstuvw " + a + " xyz";
Console.WriteLine(b);
IL_0000: ldstr "abcdefghijklmnopqrstuvw I change per class or method xyz"
IL_0005: call System.Console.WriteLine
IL_000A: ret
This will store many different strings since it looks like they're concatenated during compile time, so you will have many "similar" copies of this same string except the a
part of it will be different. The advantage is that there is no string.Format
call.
How can I evaluate the benefits of doing it one way vs the other way? Do benchmarks for this type of thing already exist?
a
in runtime:string a = new string('I', 1) + " change per class or method";
. Sob
cannot be concatenate in compile time. – Annorahconst
accomplishes what you wanted. Although then it interns strings "abc" and "xyz" separately. I'm starting to see there are a lot of combinations of how this could end up being more or less efficient... hrmm – CuculiformSystem.Text.StringBuilder
- it's the right tool to use when concatenating strings very often. "Money" is in quotes because I'm talking about the overall cost of design/implementation versus run time - it's a bit like comparing apples and aardvarks, but, you still can. – Cardon