Someone explain this to me - string.Format compared to concatenation



  • @Magus said:

    If that's done in the compilation,

    How could it be? EDIT: to clarify, the format string isn't required to be a string constant-- you can pass in any string you like.

    I guess they could do a little JIT compilation of it, but that seems like a lot of work for such a tiny use-case.



  • @Magus said:

    It depends on when that's done. If that's done in the compilation, it shouldn't be any worse.

    I originally did say that. But, I rather doubt that the compiler would be smart enough to: inline the function call to string.Format, determine that the static format string would result in a static execution path within that function, get rid of all the code that wouldn't run, and then optimize that path to something at least as efficient as simply concatenating the strings.


  • Java Dev

    Is there any need for stringbuilder to keep the result contiguous in memory until .toString() has been called? It can just contain a list of pieces and a total length, so it only needs to copy each byte twice (or even once, if it just collects references to the original appended strings)



  • No mention of String.Concat() ? Definitely my favourite from a style perspective, and much cleaner for the given use case.

    "Excessive" + "use" + "of" + "this" normally means things are about to get ugly.


  • kills Dumbledore

    C# converts addition to String.concat() in a fairly clever way.



  • @PleegWat said:

    Is there any need for stringbuilder to keep the result contiguous in memory until .toString() has been called? It can just contain a list of pieces and a total length, so it only needs to copy each byte twice (or even once, if it just collects references to the original appended strings)

    It has done both in the past. This is from @Jaloopa's second link:

    The StringBuilder object is carefully designed to have linear, not quadratic, performance in this scenario. (How it achieves this has changed over the years; in the past it has used a double-when-full strategy. More recently I believe it uses a linked list of large blocks.

Log in to reply