简体   繁体   中英

When to use string concat

I have read quite a few articles on +, stringbuilderappend and concat. But, if I have just one single concatenation to do what is the best option?

  1. str1 + str2
  2. Use string builder
  3. Use string concat

I am looking for the explanation when only and only 2 strings are involved.

Also when 2 strings are involved is the complexity of String concat O(n) where n is the length of the longest string?

If you're just doing a single concatenation, use str1 + str2 . This is easy to read, and will be translated to string concat by the compiler, which is perfectly fine if you're not going through a loop or something. In fact, it's faster than using a StringBuilder if you're only going to concatenate strings a single time.

See http://blog.codinghorror.com/the-sad-tragedy-of-micro-optimization-theater/ for a description of why you shouldn't bother using a string builder if you're not looping.

Also when 2 strings are involved is the complexity of String concat O(n) where n is the length of the longest string?

You could say that. I'd say it's O(n) where n is the combined length of the two strings, but since the shortest string cannot, by definition, be an order of magnitude larger than the longest string then it all comes out the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM