Java中方法的内存分配

时间:2013-12-12 07:04:47

标签: java memory-management

假设我们有以下课程:

class SomeClass 
{
    //some fields

    public Datatype getThing (Datatype A){
        Datatype B, C... ;
        //code snippet that involves processing A, B, C... to get P, Q
        //code snippet that involves processing P, Q to get X
        //code snippet that processes X to get Y
        return Y;
    }
    public String getThings1 (Datatype A)
    {
        Datatype B, C... ;
        //code snippet that involves processing A, B, C... to get P, Q
        //code snippet that involves processing P, Q to get X
        //code snippet that processes X to get Y
        //*NEW* code snippet that processes P, Y to get Z
        return Z;
    }
    public String getThings2 (Datatype A)
    {
        Datatype B, C... ;
        Datatype Y = getThing (A);
        //*REPEATED code snippet that involves processing A, B, C... to get P
        //*NEW* code snippet that processes P, Y to get Z
        return Z;
    }
}

getThings1和getThings2都做同样的事情。但哪个是首选实施?

我觉得应该尽可能避免代码重复。但是getThings2中的双内存分配是否真的可取? (假设涉及的数据类型可以是大型列表或对象本身?)

2 个答案:

答案 0 :(得分:2)

由于垃圾收集,这两种方法都没有明显优于其他方法。在这种情况下,代码质量(可读性,可重用性,较少的代码重复)应该是选择一种实现而不是另一种实现的基础。

答案 1 :(得分:2)

Methods do not live on the heap.

方法由Java字节代码组成。对于每个类的实例都是一样的。无需为每个对象创建单独的字节代码副本。创建新对象时,不需要为方法代码分配内存。堆上的对象由一块足够大的内存块组成,包含对象的非静态成员变量

对于方法中使用的局部变量,在调用方法时使用堆栈。