Instance Variable vs Local Variable

From: Paul Carey (ociardhp_at_online.ie)
Date: 12/03/03


Date: 3 Dec 2003 06:44:16 -0800

Hi

When delegating a compareTo method for a playing card to a Comparator, I
wasn't sure whether to go for the instance variable or local variable approach:

public class Card implements Comparable
{
    static class SortByValueThenSuit implements Comparator
    {
        public int compare(Object o1, Object o2)
        {
            ...
        }
    }

    // local variable approach
    public int compareTo(Object o)
    {
        return new SortByValueThenSuit().compare(this, o);
    }
    
    
    // instance variable approach
    private SortByValueThenSuit sorter = new SortByValueThenSuit();
    public int compareTo(Object o)
    {
        return sorter.compare(this, o);
    }
}

With only 52 cards in the deck and with a fairly limited number of comparisons,
maybe the local variable option would be considered better for reasons of
encapsulation and because the Comparator will be automatically marked for
garbage collection once the method has exited. But I'm curious to know under
what kind of circumstances might the overhead of creating a new Comparator
every time compareTo is invoked mean that the instance variable approach
would be preferable. If there are a very large number of objects to be sorted
and sorting occurs regularly, am I going to be wasting memory, or is the fact
that the Comparator contains no instance variables itself relevant?

Many thanks

Paul