Net micro - how are duplicate strings handled?

This is a general question about saving application memory space.

  if (useDebug) { Debug.Print("SpiderIP: " + ipAddress + " MAC: " + smac + " Event count: " + ONevent.ToString()); }

  //Inform operator of our IP Address
  display_T35.SimpleGraphics.DisplayText("SpiderIP: " + ipAddress + "  MAC: " + smac, NBFont, Colors.Blue, 3, 34); 

  string s = "SpiderIP: ";
  if (useDebug) { Debug.Print(s + ipAddress + " MAC: " + smac + " Event count: " + ONevent.ToString()); }

  //Inform operator of our IP Address
  display_T35.SimpleGraphics.DisplayText(s + ipAddress + "  MAC: " + smac, NBFont, Colors.Blue, 3, 34); 

I ask because I tend to use alot of strings for Debug.Print and whatever…

Is it better to use - string s = "SpiderIP: "; ?


Actually the biggest issue (if you can call it that - just a constraint really) is that each string “+” operation creates and destroys strings. If you are ever stepping into code and you do this on a string character, you’ll see a flood of string operations being called.

So in this case, perhaps the best outcome is to create your mass of strings once and print it out to both locations once. I don’t know how often you’re going to use “SpiderIP:” outside this actual section of code so you’re not going to massively gainvalue in it’s multiple-reuse (just the two operations here)

@ Brett -

Thanks… Good advice.

Yes, I have noticed the flood of operations. The examples posted would only occur once but I use similar
code to update the display on data received from a module.

I was wondering about how identical strings are stored in code.

Say I used “Content is identical” in my code 10 times.

Does the application code compiler (proper term?) store only one string content and then use it 10 times?
Or are 10 different strings stored in code.

Maybe I do not know how to ask the question properly…

The way I’d ask that question is “does the IL contain 10 strings all the same (and therefore use my memory excessively) or is it smart enough to store it once - and what is the best approach to dealing with this?”

I know that the Windows impl of .NET keeps only one copy of identical strings in memory, and reuses it.
But I don’t know how this is managed in NETMF.

The term you’re looking for is “string interning”. On the desktop framework, strings are interned. I don’t know about NETMF, but you should be able to check like this:

var s1 = "this is a string";
var s2 = "this is a string";
var s3 = "this is" + " a string";
var s4 = "this " + "is a string";

Console.WriteLine(object.ReferenceEquals(s1, s2)); // true if string constants are interned
Console.WriteLine(object.ReferenceEquals(s3, s4)); // true if all strings are interned

Brett is right, though. Keep string construction to an absolute minimum. It’s enormously destructive to performance.

Thank you all for your input.