Most efficient way to concatenate strings?

后端 未结 17 1572
野趣味
野趣味 2020-11-22 03:04

What\'s the most efficient way to concatenate strings?

17条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 03:59

    Adding to the other answers, please keep in mind that StringBuilder can be told an initial amount of memory to allocate.

    The capacity parameter defines the maximum number of characters that can be stored in the memory allocated by the current instance. Its value is assigned to the Capacity property. If the number of characters to be stored in the current instance exceeds this capacity value, the StringBuilder object allocates additional memory to store them.

    If capacity is zero, the implementation-specific default capacity is used.

    Repeatedly appending to a StringBuilder that hasn't been pre-allocated can result in a lot of unnecessary allocations just like repeatedly concatenating regular strings.

    If you know how long the final string will be, can trivially calculate it, or can make an educated guess about the common case (allocating too much isn't necessarily a bad thing), you should be providing this information to the constructor or the Capacity property. Especially when running performance tests to compare StringBuilder with other methods like String.Concat, which do the same thing internally. Any test you see online which doesn't include StringBuilder pre-allocation in its comparisons is wrong.

    If you can't make any kind of guess about the size, you're probably writing a utility function which should have its own optional argument for controlling pre-allocation.

提交回复
热议问题