Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

code optimization  RSS feed

 
raj baig
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am trying to optimize my code,can you tell me which is the best way of
doing

I am calling a method of a class more no of times in my code which
returns me a object





1. A a=b.getAObject();
a.getId();
2. new B().getAObject().getId()

here if i have to call getId method more times is it better to
once A object and using a ref call method.
or
instead of creating object directly call : new B().getAObject().getId()


Thanks in Advance
Raj
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general it's good practice to avoid object creation if possible. If it's feasible to keep a reference to a B object around, use that for repeated invocations of the getAObject method.

Having said that, recent JVMs have become much faster at object creation, so unless the B constructor does a lot of setup work, this may not make a noticeable difference.
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends, whether b.getAObject() is giving you exactly the same object everytime or not. If not then you have to get it every time, otherwise you might get errors. If yes then its, indeed, better to get it once and use it further. Furthermore, even if it doesn't affect your performance then still you should be reasonable while writing code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!