简体   繁体   English

何时使用字符串concat

[英]When to use string concat

I have read quite a few articles on +, stringbuilderappend and concat. 我已经读了很多关于+,stringbuilderappend和concat的文章。 But, if I have just one single concatenation to do what is the best option? 但是,如果我只有一个串联来执行,最好的选择是什么?

  1. str1 + str2 str1 + str2
  2. Use string builder 使用字符串生成器
  3. Use string concat 使用字符串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? 另外,当涉及2个字符串时,字符串concat O(n)的复杂度在哪里,其中n是最长字符串的长度?

If you're just doing a single concatenation, use str1 + str2 . 如果仅执行单个串联,请使用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. 这很容易阅读,并且会被编译器翻译为字符串concat,如果您不经历循环之类的事情,那将是很好的选择。 In fact, it's faster than using a StringBuilder if you're only going to concatenate strings a single time. 实际上,如果仅一次连接字符串,它比使用StringBuilder更快。

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. 请参阅http://blog.codinghorror.com/the-sad-tragedy-of-micro-optimization-theater/,以获得有关为什么不循环使用时不使用字符串生成器的原因的说明。

Also when 2 strings are involved is the complexity of String concat O(n) where n is the length of the longest string? 另外,当涉及2个字符串时,字符串concat O(n)的复杂度在哪里,其中n是最长字符串的长度?

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. 我想说的是O(n) ,其中n是两个字符串的组合长度,但是根据定义,由于最短的字符串不能比最长的字符串大一个数量级,因此所有结果都是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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