Do accessors lower performance?

Z

Zhao

I am wondering how the latest Java compiler/JVM deal with accessor
(getXXX setXXX). Is there any overhead using them comparing to making
class members public and access them directly?

thanks
 
M

Marco Schmidt

Zhao:
I am wondering how the latest Java compiler/JVM deal with accessor
(getXXX setXXX). Is there any overhead using them comparing to making
class members public and access them directly?

Depends. If your getXXX is called often, it may get inlined by the JIT
compiler. Then there's no overhead. It probably helps if you declare
the getXXX method as final.

Anyway, I would do measurements before sacrificing good data
abstraction practices like encapsulating data fields with getters and
setters.

If you work a lot on a specific data structure, maybe it's a good idea
to copy its content, let the algorithm work directly on the copy and
write it back after that.

Regards,
Marco
 
M

Michael Borgwardt

Zhao said:
I am wondering how the latest Java compiler/JVM deal with accessor
(getXXX setXXX). Is there any overhead using them comparing to making
class members public and access them directly?

Practically none. Don't worry about it.
 
R

Robert Olofsson

Zhao ([email protected]) wrote:
: I am wondering how the latest Java compiler/JVM deal with accessor
: (getXXX setXXX). Is there any overhead using them comparing to making
: class members public and access them directly?

Hotspot inlines quite much nowdays. If you really care about
performance I suggest you get a profiler and try to measure the cost
of the accessors, most of the time there wont be any such cost.

However if you profile your application from start to finish with
method tracing enabled hotspot will not inline code. You have to start
your application without method tracing and enable it after some time
to see what got inlined. This is kind of evil, since this means that
many will profile and find a trace that does not look like the one on
the production server....

/robo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top