Reputation: 9548
In C/C++ we have realloc
which will efficiently allocate additional space for an existing collection. I guess it is sub linear (or even constant) in complexity.
Is there a way to achieve the same in Java? Here are the items that I looked at,
System.arrayCopy
as well as Arrays.copyOf
ArrayList
must be same as point 2 above.Note : My requirement is to expand possibly an extremely large array to even further.
Upvotes: 2
Views: 603
Reputation: 106351
realloc
is likely to be O(n) in practice, since it sometimes/often involves memory copying. In that sense, it's equivalent in theoretical complexity to allocating a new array in Java.
Now Java always zeros the newly allocated memory which may take it a bit longer, but OTOH the GC has insanely fast memory allocations so it may even be faster than realloc
in some cases. I'd expect a strategy that involves allocating new arrays in Java to be overall roughly comparable in speed to realloc
. Possibly Java is better for smaller arrays, C/C++ would have the edge for big arrays, but YMMV. You'd have to benchmark in your particular implementation and workload to be sure.
So overall:
ArrayList
does internally.Final but important point: unless you are writing very low level code, you probably shouldn't be worrying about this anyway. Just use one of the fine collection classes that already exist (Java Collections, Google Collections, Trove etc.) and let them handle all of this stuff for you.
Upvotes: 5