c# - Is it true that StringBuilder is slower than concatenate a dozen of strings? -
is true stringbuilder slower concatenate dozen of strings? how compiler optimize string concatenation joining dozen of strings using "+" better stringbuilder?
from book (written ben watson) says that:
string concatenation: simple concatenation of known (at compile time) quantity of strings, use ‘+’ operator or string.concat method. more efficient using stringbuilder. string result = + b + c + d + e + f; not consider stringbuilder until number of strings variable , larger few dozen. compiler optimize simple string concatenation in way lessen memory overhead.
string.concat more efficient because knows string lengths start. can allocate single buffer right length, copy strings , return buffer.
stringbuilder has allocate small buffer, reallocating , copying everytime call append causes run out of space. final call tostring() has allocate yet buffer.
so use string.concat when know in advance how many strings have; use stringbuilder when don't.
in c#, chained calls + operator automatically converted single call string.concat.
Comments
Post a Comment