Should I use string constants or string literals

好久不见. 提交于 2019-12-19 08:29:25

问题


By default I use string constants in my code when I have a string of text that will be output to the screen via a messagebox, label, etc. My main reason for doing so is that I do not want these strings to change at runtime and this way nobody really touches them.

My question is:

It seems that from a memory point of view, this approach is creating an object whose lifetime will be decided by the GB whereas a string literal seems more efficient and will be disposed of more quickly. I know this is a rookie question but is there a benefit (no matter how tiny) when using a literal over a constant or should a constant be used in such scenarios.

I know it will not make any noticeable difference in my apps but I am trying to improve myself as a dev and build standards that I keep a reasonable amount of the time. :o)


回答1:


Neither. The recommended way AFAIK is to use a resources file.




回答2:


Prefer string constants to string literals, but the reason is to make your code more maintainable, not to improve its performance.




回答3:


You should look into "string interning". Basically, all of the unique string literals (constant or inline) in any of your source files will be stored in a special table. They will never be garbage collected, and may benefit from re-use.

You might want to look into using a resources file if you will ever be changing those strings without wanting to recompile (eg for internationalisation)




回答4:


It would depend on whether you need these strings to be localizable or not. If you need the ability to translate your software into other languages, then I would place as many strings that are displayed to an end user as you can in resource files. If you do not need localization, or if the strings in question are never displayed to an end user, I would use constants. If your strings are shared amongst multiple classes, I would create classes that wrap up common strings that are provided as public constants. Unless these strings need to be used outside of the assembly they are defined in, keep them at the lowest privilege level possible (private, protected, internal).




回答5:


For internationalization purposes, it's true that the accepted best practice/recommendation is a set of resource files.

I am following the same pattern of using string constants in their own class. I find it's easier to create consts that'll be used on multiple pages throughout the web app. Even a const with placeholders helps!

  //{1} for the user's full name for example
const string SOME_LABEL = "Thanks for purchasing {0} products, {1}!";


来源:https://stackoverflow.com/questions/1166254/should-i-use-string-constants-or-string-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!