Sunday 15 July 2012

variables - Performance gain using public attributes in java? -



variables - Performance gain using public attributes in java? -

so,

i've got class called intrectangle holds int x1, int x2, int y1, int y2.

this assumption:

if create attributes above public performance boost, since don't have force , pop things when accessing them. i'll give shot.

public class crapmain { public void start () { intrectangle rec = new intrectangle (5, 10, 6, 12); int value = 0; double time = system.nanotime(); (int = 0; < 1000000000; i++){ value = rec.x1; } time = system.nanotime() - time; system.out.println(time); } public static void main(string[] args) { new crapmain().start(); } }

it prints 2559391.0

if create attributes private, create getters them , alter "value = rec.x1;" "value = rec.getx1();" prints 3551075.0

so there's performance boost given.

however, makes code venerable, since it's easy alter attributes mistake.

my question is, worth it? , mutual practice among programmers writing high-performance code?

are sure benchmark measures think does? microbenchmarks can become incredibly hard right.

your benchmark measures code before hotspot has kicked in , optimised code. infact odds have benchmarked java interpreter , not execution time after jit has compiled code native assembler.

modern jvms can optimise getter methods out, or inline them; after jvm has 'warmed up' plenty have collected plenty statistics uses optimise 'hotspots' in code. typically method has run on 10 one thousand times before optimisation. method invoked once, , has big loop in it, not exit method. means if jvm wanted optimise loop while running have perform 'on stack replacement' (osr), can , happen not in real production code. when happen, osr optimised code different non-osr optimised code, has different performance characteristics.

so, in summary not clear there performance benefit experiment stands.

for advice on how improve benchmark, see how write right micro-benchmark in java?

that said, if there performance gain, worthwhile? depends on context, how many times 1 making phone call , performance requirements section of code , project? vast bulk of cases, code clarity wins hands down.

java variables

No comments:

Post a Comment