Most memory efficient way to grow an array in Java?

前端 未结 12 1273
陌清茗
陌清茗 2020-12-13 19:18

I\'m not too concerned about time efficiency (the operation will be rare), but rather about memory efficiency: Can I grow the array without temporarily having all th

12条回答
  •  心在旅途
    2020-12-13 20:17

    Is there a more efficient way to grow a large array than creating a new one and copying over all the values? Like, concatenating it with a new one?

    No. And probably there is no language, that guarantees growing an array will always take place without copying. Once you allocate the space for the array and do something else, you most likely have other objects in memory right after the end of the array. At that point, it's fundamentally impossible to grow the array without copying it.

    What about having fixed-size arrays stored in another array and reallocate / copy that top-level one? Would that leave the actual values in place?

    You mean have an array of arrays and treat it as one large array consisting of a concatenation of the underlying arrays? Yes, that would work (the "faking it by doing indirection" approach), as in Java, Object[][] is simply an array of pointers to Object[] instances.

提交回复
热议问题