• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

code optimization

 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Rancher
Posts: 43027
76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic