内存管理递归Java

我正在使用大型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));
}

这会有效吗,即GC会删除大名单吗?

最佳答案
看起来像divide & conquer.在这种情况下,最好通过使用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));
}

转载注明原文:内存管理递归Java - 代码日志