Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In the case you present, it's actually better to use the concatenation operator on the string class. This is because it can pre-compute the lengths of the strings and allocate the buffer once and do a fast copy of the memory into the new string buffer.</p> <p>And this is the general rule for concatenating strings. When you have a set number of items that you want to concatenate together (be it 2, or 2000, etc) it's better to just concatenate them all with the concatenation operator like so:</p> <pre><code>string result = s1 + s2 + ... + sn; </code></pre> <p>It should be noted in your specific case for s1:</p> <pre><code>string s1 = "foo" + "bar"; </code></pre> <p>The compiler sees that it can optimize the concatenation of string literals here and transforms the above into this:</p> <pre><code>string s1 = "foobar"; </code></pre> <p>Note, this is only for the concatenation of two string literals together. So if you were to do this:</p> <pre><code>string s2 = foo + "a" + bar; </code></pre> <p>Then it does nothing special (but it still makes a call to Concat and precomputes the length). However, in this case:</p> <pre><code>string s2 = foo + "a" + "nother" + bar; </code></pre> <p>The compiler will translate that into:</p> <pre><code>string s2 = foo + "another" + bar; </code></pre> <p>If the number of strings that you are concatenating is variable (as in, a loop which you don't know beforehand how many elements there are in it), then the StringBuilder is the most efficient way of concatenating those strings, as you will always have to reallcate the buffer to account for the new string entries being added (of which you don't know how many are left).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload