String vs. StringBuilder

后端 未结 24 1553
眼角桃花
眼角桃花 2020-11-22 06:22

I understand the difference between String and StringBuilder (StringBuilder being mutable) but is there a large performance difference

24条回答
  •  Happy的楠姐
    2020-11-22 06:59

    Using strings for concatenation can lead to a runtime complexity on the order of O(n^2).

    If you use a StringBuilder, there is a lot less copying of memory that has to be done. With the StringBuilder(int capacity) you can increase performance if you can estimate how large the final String is going to be. Even if you're not precise, you'll probably only have to grow the capacity of StringBuilder a couple of times which can help performance also.

提交回复
热议问题