String assembly by StringBuilder vs StringWriter and PrintWriter

后端 未结 6 1351
孤城傲影
孤城傲影 2020-12-04 16:36

I recently encountered an idiom I haven\'t seen before: string assembly by StringWriter and PrintWriter. I mean, I know how to use them, but I\'ve always used StringBuilder

6条回答
  •  情书的邮戳
    2020-12-04 17:13

    Stylistically, the StringBuilder approach is cleaner. It is fewer lines of code and is using a class that was specifically designed for the purpose of building strings.

    The other consideration is which is more efficient. The best way to answer that would be to benchmark the two alternatives. But there are some clear pointers that StringBuilder should be faster. For a start, a StringWriter uses a StringBuilder StringBuffer under the hood to hold the characters written to the "stream".

提交回复
热议问题