String.Format or Not? [duplicate]

岁酱吖の 提交于 2019-12-05 07:54:10

If you're ever going to localize your application (and it's often hard to rule that out at the start), then String.Format is to be much preferred, for two reasons:

  1. You have only one string literal to translate
  2. You can change the order of the values, which may make more sense in another language.

Everyone has posted about how readable string.format is (which I accept, and it has null ref and internationalisation benefits yes) but nobody has mentioned that it's considerably slower than simple string concatenation (small number of elements) or using StringBuilder (large number of concats).

If performance matters or you're doing a large number of operations (so performance soon will matter) then you should avoid format.

Edit: References as requested ;)

http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/formatting-strings.aspx

http://blog.briandicroce.com/2008/02/04/stringbuilder-vs-string-performance-in-net/

Nice article here by Karl Seguin: code better - use string.format explaining some of the benefit.

The first method is very hard to read and even more of a bore to type. As well, once you start doing a lot of those concatenations, there are performance considerations to think about.

If you are actually formatting values ({0:d} etc.), String.Format is a lot better to read than string concatenation.

For me it depends on the contents. Concatenating strings does create additional string objects (because strings are immutable in .NET), though mainly it's a readbility issue.

Sometimes it gets complicated when you want to place newline characters in a string, in which case I tend to use something like:

StringBuilder.AppendLine(string.Format("Some text {0}.", "here"));

Personally I find that String.Format is easier to read, the string is presented as one consecutive text. It depends though on how many parameters there are, if you need to hunt for the right parameter to understand it, then ...

I believe its more of a matter of preference. However once I started using it regularly most of my team followed suit. When we discussed it it was agreed that is just easier to understand and read.

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