Currently, the "growing" algorithm figures out that the Array
backing the ArrayList
/ArrayBuffer
is too small for the requested operation and copies the contents to the beginning of a larger array.
jsuereth explains it very well in the comments of this thread:
ArrayBuffer is great for append but not as good for prepend. Java's ArrayList will actually try to amortize costs to prepend as well, making it slightly better in my opinion. Yes ArrayBuffer is probably good enough if you're just appending on to a list and indexing elements.
Wouldn't it be a good enhancement to make the location of the old contents depend on the last operation, based on the assumption that this operation might be called more often in the future?
I. e.:
if
append
needs a larger array, copy the existing contents to the front of the new array:[x|x|x|x|x|x] | v [x|x|x|x|x|x| | | | | ]
if
prepend
needs a larger array, copy the existing contents to the back of the new array:[x|x|x|x|x|x] | v [ | | | | |x|x|x|x|x|x]
Will this solve the performance problems for prepend, while generally making the algorithm a bit more adaptive to usage patterns? (Worst case would be alternatively appending/prepending large stuff ...)
Are there any other data structures which already take the last operation into account when growing the underlying structure?