jens
jens

Reputation: 17565

Java = Getter/Setter = Does this increase "object size" at runtime and accesstime (CPU Cycles?)

i need to write an ajax applicatoin, where on the server side (implemented in java) millions of small objects will be created and held in memory. normally I use the beanstyle (with getter / setter) for any objects.

My question: Does it make a difference (in regard to memory usage and CPU Time for access) at runtime, having getter/setter methods for an instanciated object versus not having them and directly accessing the fields/members? For example if having getter/setter makes an object bigger for 5bytes per method and instance, then this would dramatically add up in total with millions ob objects. The same with accessing a getter vers directly accesing the member/variable in regard to cpu cycles.

public String myvartoaccess;

vs

private String myvartoaccces;
public String getMyvartoaccess();

Thanks very much! Jens

Upvotes: 3

Views: 2395

Answers (4)

Kevin Lacquement
Kevin Lacquement

Reputation: 5117

A getter and setter will add a small amount to the size of the class; however, the size of the individual objects will not be affected. So whether you have a single object or ten thousand, the memory cost of the method will be added exactly once.

As for the CPU overhead, there will be a small overhead; however, this should be optimized and negligible.

Upvotes: 7

irreputable
irreputable

Reputation: 45433

No difference. JVM will optimize the getter as if it's a field read.

Upvotes: 4

WhiteFang34
WhiteFang34

Reputation: 72039

Getter and setter methods shouldn't make the objects larger, just the class that represents those objects. It's unlikely going to matter to your performance to have getter and setter methods, especially since the JVM should optimize that out. If you're concerned about performance or memory then you should load test and profile your application. Most likely you'll find a problem elsewhere, I really wouldn't worry too much about this part.

Upvotes: 0

Justin Waugh
Justin Waugh

Reputation: 4163

Getters and setters do not affect memory usage. The method implementations of getter/setter are stored with the Class of which there is only one (in a given classloader). The instances only store the state of the object.

Regarding performance, I doubt it would be significantly slower to call simple getter/setters. I would definitely first implement with the getters and setters, and then if you find it is too slow, you could potentially do away with them. Premature optimization is the root of all evil after all.

Upvotes: 1

Related Questions