Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Short answer: it depends.</p> <p>Long answer: <strong>if you already have an array of strings to concatenate together (with a delimiter), <code>String.Join</code> is the fastest way of doing it.</strong></p> <p><code>String.Join</code> can look through all of the strings to work out the exact length it needs, then go again and copy all the data. This means there will be <em>no</em> extra copying involved. The <em>only</em> downside is that it has to go through the strings twice, which means potentially blowing the memory cache more times than necessary.</p> <p>If you <em>don't</em> have the strings as an array beforehand, it's <em>probably</em> faster to use <code>StringBuilder</code> - but there will be situations where it isn't. If using a <code>StringBuilder</code> means doing lots and lots of copies, then building an array and then calling <code>String.Join</code> may well be faster.</p> <p>EDIT: This is in terms of a single call to <code>String.Join</code> vs a bunch of calls to <code>StringBuilder.Append</code>. In the original question, we had two different levels of <code>String.Join</code> calls, so each of the nested calls would have created an intermediate string. In other words, it's even more complex and harder to guess about. I would be surprised to see either way "win" significantly (in complexity terms) with typical data.</p> <p>EDIT: When I'm at home, I'll write up a benchmark which is as painful as possibly for <code>StringBuilder</code>. Basically if you have an array where each element is about twice the size of the previous one, and you get it just right, you should be able to force a copy for every append (of elements, not of the delimiter, although that needs to be taken into account too). At that point it's nearly as bad as simple string concatenation - but <code>String.Join</code> will have no problems.</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