Click here to Skip to main content
15,887,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I'm a newbie in programming. I'm thinking about the performance of a java program in terms of its load time,memory usage etc.

Which programming style will give better performance:

a) put every line of code into constructor for example :

JavaScript
Class abc 
{
   -component declarations-
  
   abc() //constructor
  {

    -all the codes line by line-
  }
}


b) As I want my code to look more organized, I create methods to be called in the
constructor for example:

JavaScript
Class abc
{
   -component declarations-

   abc() //constructor
  {
    method1();
    method2();

  }
}


I run the program by creating the object in the main function.
So which one will give better performance?


Thx for any help and guidance ^.^
Posted
Updated 8-Aug-11 4:59am
v3
Comments
LittleYellowBird 8-Aug-11 10:59am    
Added some code blocks. :)

Always code in the way that will make code the most maintainable while still providing all the necessary functionality. Never create spaghetti code which is what you will get if you put all your code in the constructor.
 
Share this answer
 
Comments
Espen Harlinn 9-Aug-11 10:35am    
Good advice, my 5
I really don't think there's a "performance" difference between these two "methods"."

Anyway, it seems you're doing sequential coding, I'm not saying you shouldn't, but if you're trying to learn you maybe look into Object-oriented programming and Multitier architecture

That might be a good start.
 
Share this answer
 
Obviously style (b) involves the overhead of two function calls (passing arguments and allocating local variables) and might give the compiler less opportunities for global optimizations.

In practice this overhead is often neglectable.

What really matters is indeed to achieve a correct structuring of your code for readability and maintenability.

If method1 and method2 are never used elsewhere than in the constructor and will never be, you can question the benefit to create them, except for the sake of keeping small functions.

Alternatively, you could just enclose the chunks of code in a local block {}.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900