user2212990
user2212990

Reputation: 177

In Java, is it worthy to store a field from another class in a field in my class?

Suppose I have a java class (which we will call ThatClass) with a lot of static final fields (none of them value fields though) and suppose that I access a lot of those fields, a lot of times each, from methods in a class which we will call ThisClass. Considering a situation where both memory use and performance are critical, is it worthy to store the static final fields from ThatClass that are used inside methods of ThisClass as fields in ThisClass?

Example:

public class ThatClass
{
    public static final Foo field1 = new Foo();
    public static final Foo field2 = new Foo();
    public static final Foo field3 = new Foo();
}


//implementation A
public class ThisClass
{
    public ThisClass()
    {
        for (int i = 0; i < 20; ++i)
        {
            Bar(ThatClass.field1, ThatClass.field2, ThatClass.field3);
        }
    }

    public void Bar(Foo arg1, Foo arg2, Foo arg3)
    {
        // do something.
    }

    /* imagine there are even other methods in ThisClass that need to access the
     * fields of ThatClass.
     */
}

now this other implementation of ThisClass

//implementation B
public class ThisClass
{
    private final Foo myField1;
    private final Foo myField2;
    private final Foo myField3;

    public ThisClass()
    {
        myField1 = ThatClass.field1;
        myField2 = ThatClass.field2;
        myField3 = ThatClass.field3;

        for (int i = 0; i < 20; ++i)
        {
            Bar(myField1, myField2, myField3);
        }
    }

    public void Bar(Foo arg1, Foo arg2, Foo arg3)
    {
        // do something.
    }

    /* imagine there are even other methods in ThisClass that need to access the
     * fields of ThatClass.
     */
}

I know I wouldn't need to pass the three fields as arguments for the method Bar in implementation B, but for the sake of this discussion, imagine that was a necessity.

Questions:

  1. Is there any difference regarding performance between the two implementations? Is B faster than A?

  2. Regarding memory cost, B demands more memory than A? I'd imagine it does, but just a little more (one extra reference for each extra field in B. Each reference being the size of an int, right?)

Thanks!

Upvotes: 0

Views: 120

Answers (1)

Tom McCann
Tom McCann

Reputation: 36

+1 to what Russell said. Furthermore, having the fields defined in two places violates the DRY principle (Wikipedia). You give a very trivial example, but imagine you need to change the definition of one of those static fields. With the second implementation you have to update the code twice - assuming you remember you have two definitions of the same field.

Upvotes: 1

Related Questions