开发者

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

开发者 https://www.devze.com 2023-03-20 20:38 出处:网络
was wondering which of the following options is more effic开发者_Python百科ient. Any suggestions?

was wondering which of the following options is more effic开发者_Python百科ient. 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", ...);
....


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)


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).


I doubt there's much in it but Listing 1 I would say because all those individual strings in listing 2 would have to be created in turn unless the optimiser is doing things behind the scenes.

I'd got with version one but use a const instead if the value is not to change.

const string HEADER  = "Header 1";


Strings will be re-used (interned). So they should both be equally as efficient. I'd argue that Listing 1 is more maintainable.


Both are the same. Strings are interned.


Im not 100% sure but i think its about the same thing you could add const to your string declaration if you want more performance but i don't think you will be able to see any measurable difference..

But Listing 1 has one benefit that you can change the value by just changing one part of the code...


The first option is more efficient for the purposes of refactoring, you only have one line to change if you ever wish to change the code. Additionally if its always going to be the same value defined at compile time you may want to consider using a constant.


If you really believe this piece of code is a performance bottleneck, you should try it both ways, profile, and then you'll know which is more efficient.

If you don't care enough to measure, do not optimise.

If you're just asking out of curiosity, Strings get interned in .NET so it's exactly the same from a performance viewpoint either way - i.e. don't do the second one because then whoever has to maintain it will kill you.

0

精彩评论

暂无评论...
验证码 换一张
取 消