中增长数组的最有效内存方式

中增长数组的最有效内存方式

本文介绍了在 Java 中增长数组的最有效内存方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太关心时间效率(这种操作很少见),而是关心内存效率:我可以在不临时拥有两次所有值的情况下增长数组吗?

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 the values twice?

有没有比创建一个新数组并复制所有值更有效的方法来增加一个大数组?比如,将它与一个新的连接起来?

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?

将固定大小的数组存储在另一个数组中并重新分配/复制顶级数组怎么样?这会保留实际值吗?

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?

我知道ArrayList,但我需要对访问数组进行大量控制,而且访问速度需要非常快.例如,我认为我更喜欢 a[i]al.get(i).

I'm aware of ArrayList, but I need a lot of control about accessing the array and the access needs to be very fast. For instance, I think I prefer a[i] to al.get(i).

我关心这个的主要原因是有问题的数组(或一些这样的数组)很可能占据了足够大的主内存部分,以至于通常的策略是在丢弃原始数据之前创建一个双倍大小的副本可能行不通.这可能意味着我需要重新考虑整体策略(或我的硬件建议).

The main reason why I care about this is that the array in question (or a number of such arrays) might very well occupy a large enough portion of main memory that the usual strategy of creating a double sized copy before discarding the original might not work out. This may mean that I need to reconsider the overall strategy (or up my hardware recommendations).

推荐答案

没有.并且可能没有语言可以保证数组的增长总是在不复制的情况下发生.一旦你为数组分配了空间并做其他事情,你很可能在数组结束之后在内存中还有其他对象.到那时,不复制数组就根本不可能增长它.

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.

固定大小的数组怎么样存储在另一个数组中并重新分配/复制那个顶级的?会是保留实际值?

您的意思是有一个数组数组并将其视为一个由底层数组串联组成的大数组?是的,这行得通(通过间接方式伪造"方法),就像在 Java 中一样,Object[][] 只是一个指向 Object[] 的指针数组实例.

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.

这篇关于在 Java 中增长数组的最有效内存方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:55