StringBuilder.Append Vs StringBuilder.AppendFormat

前端 未结 9 1349
轮回少年
轮回少年 2021-01-31 15:30

I was wondering about StringBuilder and I\'ve got a question that I was hoping the community would be able to explain.

Let\'s just forget about code readability, which o

9条回答
  •  长情又很酷
    2021-01-31 16:03

    casperOne is correct. Once you reach a certain threshold, the Append() method becomes slower than AppendFormat(). Here are the different lengths and elapsed ticks of 100,000 iterations of each method:

    Length: 1

    Append()       - 50900
    AppendFormat() - 126826
    

    Length: 1000

    Append()       - 1241938
    AppendFormat() - 1337396
    

    Length: 10,000

    Append()       - 12482051
    AppendFormat() - 12740862
    

    Length: 20,000

    Append()       - 61029875
    AppendFormat() - 60483914
    

    When strings with a length near 20,000 are introduced, the AppendFormat() function will slightly outperform Append().

    Why does this happen? See casperOne's answer.

    Edit:

    I reran each test individually under Release configuration and updated the results.

提交回复
热议问题