Is it better to reuse a StringBuilder in a loop?

前端 未结 14 2098
名媛妹妹
名媛妹妹 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:06

    Okay, I now understand what's going on, and it does make sense.

    I was under the impression that toString just passed the underlying char[] into a String constructor which didn't take a copy. A copy would then be made on the next "write" operation (e.g. delete). I believe this was the case with StringBuffer in some previous version. (It isn't now.) But no - toString just passes the array (and index and length) to the public String constructor which takes a copy.

    So in the "reuse the StringBuilder" case we genuinely create one copy of the data per string, using the same char array in the buffer the whole time. Obviously creating a new StringBuilder each time creates a new underlying buffer - and then that buffer is copied (somewhat pointlessly, in our particular case, but done for safety reasons) when creating a new string.

    All this leads to the second version definitely being more efficient - but at the same time I'd still say it's uglier code.

提交回复
热议问题