Sarah Szabo
Sarah Szabo

Reputation: 10825

Should I Leave Methods I Don't Use In a Class?

I have a class that is used heavily (> 400,000 instances) in a performance heavy program. Does leaving these methods in the class seriously effect memory usage for each object, or does it not really matter?

Upvotes: 3

Views: 118

Answers (2)

Joseph K. Strauss
Joseph K. Strauss

Reputation: 4913

The class is loaded into memory the first time it is used, and it is only loaded once in normal situations. In fact, the equals method of Class is written as ==, which means that Java is expecting it to be the exact same object.

This is different than class instances which get memory allocated upon instantiation and deallocated when garbage collected.

What is more of a concern would be if your class has unused fields. Each field will consume a small amount of memory, but when multiplied by the number of live instances can amount to a large chunk of memory. This is true even if the field is initialized to null. If the field is initialized to a new object then this can consume even more memory, depending on how large the objects are.

Upvotes: 3

Mark Lybarger
Mark Lybarger

Reputation: 463

The memory consumed by loading the class will correspond to the size of the code, however, the code will not be duplicated for each instance of the class.

An instance will only require as much memory as the instance attributes + some overhead for managing the object instance itself.

as was stated, there's maintenance cost and what not. it's typically better to remove dead code, however change also has a cost. consider these aspects.

Upvotes: 4

Related Questions