Why does naive string concatenation become quadratic above a certain length?

前端 未结 3 2040
梦如初夏
梦如初夏 2020-12-28 20:24

Building a string through repeated string concatenation is an anti-pattern, but I\'m still curious why its performance switches from linear to quadratic after string length

3条回答
  •  旧巷少年郎
    2020-12-28 21:11

    [XXXXXXXXXXXXXXXXXX............]
     \________________/\__________/
         used space      reserved
                          space
    

    When growing a contiguous array data structure (illustrated above) through appending to it, linear performance can be achieved if the extra space reserved while reallocating the array is proportional to the current size of the array. Obviously, for large strings this strategy is not followed, most probably with the purpose of not wasting too much memory. Instead a fixed amount of extra space is reserved during each reallocation, resulting in quadratic time complexity. To understand where the quadratic performance comes from in the latter case, imagine that no overallocation is performed at all (which is the boundary case of that strategy). Then at each iteration a reallocation (requiring linear time) must be performed, and the full runtime is quadratic.

提交回复
热议问题