Performance: Inner class does not access outer class members

Hi,

I have a inner class, but does not use its embedded reference to the object which created it.

Can somone explain this sentence?

This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary. If possible, the class should be made static.

Thanks in advance.

Deepak

[375 byte] By [deepu-jaina] at [2007-11-27 11:46:12]
# 1

nothing to explain, it's quite self-explanatory.

jwentinga at 2007-7-29 18:06:10 > top of Java-index,Java Essentials,Java Programming...
# 2

How does it makes the instances of class larger?

And what does this mean "and may keep the reference to the creator object alive longer than necessary."

And how will marking the inner class static avoid above two,

Please explain

Thanks

Deepak

deepu-jaina at 2007-7-29 18:06:10 > top of Java-index,Java Essentials,Java Programming...
# 3

Any explaination please?

deepu-jaina at 2007-7-29 18:06:10 > top of Java-index,Java Essentials,Java Programming...
# 4

I didn't know about those references...

> How does it makes the instances of class larger?

Because a reference takes a full four bytes. Not enough to even consider worrying about.

> And what does this mean "and may keep the reference

> to the creator object alive longer than necessary."

If you refer to that inner class instance from "outside", and this outer class instance is referred to from the inner class, it can't be GCed because it's still "in use" by the inner class.

Considering that you need the outside instance to have an inner class instance anyway, this is a pretty pointless consideration.

Making it static unties inner and outer instances, so no references from inner to outer are needed. But then, you also can't access the outside object for sure.

It should be a design decision whether it's supposed to be static or not, not a consideration along the lines of "you waste 4 bytes of memory". Unless it gets critical, and then you might have bigger problems elsewhere.

Hence why I didn't know: no need to care.

CeciNEstPasUnProgrammeura at 2007-7-29 18:06:10 > top of Java-index,Java Essentials,Java Programming...
# 5

When you have a non-static inner class it can reference fields and methods of the outer class(es). To do this it has to have a hidden reference field pointing to the instance of the outer class. Although this reference in anonymous, it still takes up a slot in the instance variables of the inner class, and it can make the outer class instance "reachable" as far as garbage collection is concerned.

The extra slot isn't likely to be a big deal, but retaining outer class instances otherwise unreachable could be.

So it's good practise to make your inner classes static unless there's a reason not to.

malcolmmca at 2007-7-29 18:06:10 > top of Java-index,Java Essentials,Java Programming...