Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more efficient: hard coded strings in code --or-- reusing a string reference?

Tags:

string

c#

was wondering which of the following options is more efficient. Any suggestions?

Listing 1

string header = "Header 1"; // create a string variable and reuse
client.AddMessage(header, ...);
client.AddMessage(header, ...);
client.AddMessage(header, ...);
client.AddMessage(header, ...);
client.AddMessage(header, ...);
...

Listing 2

client.AddMessage("Header 1", ...); // hard code the string in each call
client.AddMessage("Header 1", ...);
client.AddMessage("Header 1", ...);
client.AddMessage("Header 1", ...);
client.AddMessage("Header 1", ...);
....
like image 633
Benzi Avatar asked Apr 20 '26 01:04

Benzi


2 Answers

You should probably not care about this kind of (possible) micro-optimization : what matters, here, is maintenability :

  • do you have only one string ?
  • or can you have several distinct values, one day or another ?


(The compiler should optimize that for you, anyway, I suppose)

like image 77
Pascal MARTIN Avatar answered Apr 22 '26 14:04

Pascal MARTIN


Strings are interned in the .NET world, so either one will work the same way.

In other words - it makes no difference in regards to performance.

As for maintainability - if you need to change the header name, option 1 is better (DRY).

like image 41
Oded Avatar answered Apr 22 '26 16:04

Oded