Skr*_*dde 6 java memory recursion memory-management
我正在使用大型ArrayList在Java中输入一个递归.在一个递归步骤中,我将此列表拆分为两个大小各一半的列表,并将相同的方法递归地应用于两个列表.但是,由于我在拆分后不再需要大型列表,我想从内存中删除它.在这里搜索了一会儿之后,我想出了这个:
public some_object recursiveMethod(ArrayList large_List) {
//Compute the two sublists
ArrayList lower_half = lowerHalf(large_List);
ArrayList upper_half = upperHalf(large_List);
//Delete large list from memory
large_List = null;
//Recursively call on smaller lists
return procedure(recursiveMethod(lower_half),recursiveMethod(upper_half));
}
Run Code Online (Sandbox Code Playgroud)
这会有效,即GC会删除大型列表吗?
看起来像分而治之。在这种情况下,最好通过使用List.subList()(包装器,引用大型支持列表)保留一个大型列表以及轻量级子列表视图,从而避免本地(硬)引用(参数和临时对象)和 GC 开销或一对简单的索引。
如果这些子列表必须独立于原始列表进行修改,则可以在进入递归处理之前复制该大列表一次,这仍然比多个独立子列表副本更有效。
public some_object recursiveMethod(List large_List) {
//Create views of the two sublists
List lower_half = large_List.subList(0,large_List.size()/2);
List upper_half = large_List.subList(large_List.size()/2,large_List.size());
//Recursively call on list views
return procedure(recursiveMethod(lower_half),recursiveMethod(upper_half));
}
public some_object recursiveMethod2(ArrayList large_List, int begin, int end) {
//Create views of the two sublists
int size = end - begin;
int lowerBegin = begin;
int lowerEnd = begin + size/2; //exclusive
int upperBegin = lowerEnd;
int upperEnd = begin + size; //exclusive
//Recursively call on list views
return procedure(recursiveMethod2(large_List,lowerBegin,lowerEnd),recursiveMethod2(large_List,upperBegin,upperEnd));
}
Run Code Online (Sandbox Code Playgroud)