Shisa
Shisa

Reputation: 580

Memory allocation for methods in Java

Assuming we have the following class:

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;
    }
}

Both getThings1 and getThings2 do the same thing. But which is the preferred implementation?

I feel like code duplication should be avoided whenever possible. But is the double memory allocation in the getThings2 really desirable, either? (Assuming the datatypes involved can be large lists or objects themselves?)

Upvotes: 2

Views: 3907

Answers (2)

rachana
rachana

Reputation: 3424

Methods do not live on the heap.

A method consists of Java byte code. It's the same for each instance of the class. There's no need to create a separate copy of the byte code for each object. No memory needs to be allocated for the code of methods when you create a new object. An object on the heap consists of a block of memory that's large enough to contain the object's non-static member variables

For local variables that are used in a method, the stack is used at the moment you call the method.

Upvotes: 3

aquaraga
aquaraga

Reputation: 4168

Thanks to garbage collection, neither method enjoys significant advantage over the other performance-wise. In such cases, code quality (readability, reusability, lesser code duplication) should be the basis of choosing one implementation over the other.

Upvotes: 2

Related Questions