• Post Reply Bookmark Topic Watch Topic
  • New Topic

Performance  RSS feed

 
saraswathi lokam
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of using object.var(eg. myobject.myint) in a calculation,
by assigning this value to a variable and use it in the calculation will increase the performance.
Code A:
for(int i = 0; i<20000;i++)
{
sum = ( myObj.myInt )* ( (myobj.MyInt) + i )
}
Code B:
int myint;
myint = myObj.myInt;
for(int i =0; i < 20000; i++ )
{
sum = myint * ( myint + 1 )
}
Code B is more efficient.
Any comments???
 
Peter Haggar
author
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code A is accessing object references in the loop. Code B is accessing only primitive types in the loop. Primitive types are more effecient than object references.
This is a technique that can be used in performance critical code. I wouldn't code like this normally, but I would do it if I need to speed it up.
Peter Haggar
------------------
Senior Software Engineer, IBM
author of: Practical Java
 
Susan Hoover
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the effect if the object.var is not a primitive but, instead, another object reference? Is there anything to be gained, performancewise, by creating a ref to it?
Code A:

Code B:


[This message has been edited by Susan Hoover (edited January 17, 2001).]
 
saraswathi lokam
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Susan,
we can gain performance.
Code B is more efficient than code A because, now the compiler donot have to make 2 references to access doSomething() which is the case with CodeA.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!