I have some question about arrays, I’m reading some book about Java, and now I was reading about class StringBuilder, I was taught that this class saves my string in array with current capacity, in the case that the capacity is not sufficient, this class automatically increases capacity capacity = 2*(capacity + 1), when I was studying c and c++, I was taught to do the same things if I don’t have enough space in my array, but what is the logic behind this statement? why can’t I just find out how much memory do I need and then to do capacity = capacity + homMuchDoINeed(), or why not capacity = 4 * capacity, thanks in advance for the answers
I have some question about arrays, I’m reading some book about Java, and now
Share
Because then you need to allocate new memory with each insertion, so a single insertion takes linear time, and n insertions take quadratic time. If, on the other hand, you grow by a constant factor like x2 or x1.5, a single insertion takes amortized constant time, and n insertions take linear time.
Stephan T. Lavavej explains this in multiple videos, for example, this one.