c# - Is StringBuilder only preferred in looping scenarios? -


i understand stringbuilder choice concatenating strings in loop, this:

list<string> mylistofstring = getstringsfromdatabase(); var thestringbuilder = new stringbuilder();  foreach(string mystring in mylistofstring) {     thestringbuilder.append(mystring); }  var result = thestringbuilder.tostring(); 

but scenarios stringbuilder outperforms string.join() or vice versa?

var thestringbuilder = new stringbuilder(); thestringbuilder.append("is "); thestringbuilder.append("ever "); thestringbuilder.append("idea?");  var result = thestringbuilder.tostring(); 

or

string result = string.join(" ", new string[]             {                 "or", "is", "this", "a", "better", "solution", "?"             }); 

any guidance appreciated.

edit: there threshold creation overhead of stringbuilder not worth it?

it seems string.join uses stringbuilder under hood code (reflector):

public static string join(string separator, ienumerable<string> values) {     using (ienumerator<string> enumerator = values.getenumerator())     {         if (!enumerator.movenext())         {             return empty;         }         stringbuilder sb = stringbuildercache.acquire(0x10);         if (enumerator.current != null)         {             sb.append(enumerator.current);         }         while (enumerator.movenext())         {             sb.append(separator);             if (enumerator.current != null)             {                 sb.append(enumerator.current);             }         }         return stringbuildercache.getstringandrelease(sb);     } } 

so in scenario, not different much. prefer using stringbuilder when trying concat string based on conditions.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -