Is it better to reuse a StringBuilder in a loop?

前端 未结 14 2102
名媛妹妹
名媛妹妹 2020-12-04 06:46

I\'ve a performance related question regarding use of StringBuilder. In a very long loop I\'m manipulating a StringBuilder and passing it to another method like

14条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 07:23

    The fastest way is to use "setLength". It won't involve the copying operation. The way to create a new StringBuilder should be completely out. The slow for the StringBuilder.delete(int start, int end) is because it will copy the array again for the resizing part.

     System.arraycopy(value, start+len, value, start, count-end);
    

    After that, the StringBuilder.delete() will update the StringBuilder.count to the new size. While the StringBuilder.setLength() just simplify update the StringBuilder.count to the new size.

提交回复
热议问题