Saurabh Sharma
Saurabh Sharma

Reputation: 2341

Which is more efficient? (Garbage Collection)

Okay my question is the following: Say you have a class like below. During run time:
Will a new action listener be created every time the loop is being run?
Is the second class much more efficient that the first?
In the first class are there 100 new ActionListener Objects being created?

public class Foo extends JFrame {
    public Foo() {
        for (int i = 0; i < 100; i++) {
            JTextField someField = new JTextField();
            someField.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //DO SOMETHING HERE
                }
            });
        }
    }
}

VERSUS A CLASS LIKE:

public class Foo extends JFrame {
    public Foo() {
        ActionListener someActionListener = new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                //DO SOMETHING HERE
            }
        }; 
        for (int i = 0; i < 100; i++) {
            JTextField someField = new JTextField();
            someField.addActionListener(someActionListener);
        }
    }
}

Upvotes: 2

Views: 286

Answers (3)

lynks
lynks

Reputation: 5689

In the first program, you are running new ActionListener() 100 times. You will end up with 100 ActionListener objects.

In the second program, you only run new ActionListener() once. So you will only end up with 1 ActionListener object.

Clearly, in the first program, you are taking up a bunch more memory. But the programs are not equivalent, as in the first, each JTextField has its own ActionListener, where in the second, they all share one.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533472

the second example could save 1-2 KB (which is worth about 0.003 cents) but given the functionality is not the same, correctness is more important.

by comparison 1 second of your time on minimum wage is worth 0.2 cents so if you spent even a fraction of a second thinking about it, it could have been a waste of time. ;)

Upvotes: 4

Chris Dargis
Chris Dargis

Reputation: 6043

Will a new action listener be created every time the loop is being run?

In the first class, yes.

Is the second class much more efficient that the first?

The second class gives each new JTextField() object the same action listener. This is more efficient (saves some memory). However, you should know that all 100 JTextField() objects have the same action listener.

Also, if you are going to have this be the case, you should move someActionListener = new ActionListener() into the constructor of Foo

Upvotes: 1

Related Questions