• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Create an object in class or method?

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So, I'm just wondering about best practices... If I need to reference a dynamic class from a dynamic class, is it better to create an instance for each method so it gets destroyed quciker and uses less memory, or is it better to declare and create the object in the class?

1: Log delcared in class


2: Log delcared in method
 
Greenhorn
Posts: 12
Hibernate Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
of corse the first solution is the best. Why creating a lot of objects to do some work while you need only one.
 
Sheriff
Posts: 67746
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why are you worrying about performance or optimization at all? Do what makes the most sense and provides the most clarity. Then and only then, worry about performance if (and only if) there is a demonstrable performance issue.
 
Adam Outler
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How do you demonstrate a performance issue with 3 threads running, each creating and destroying objects? There must be a best practices guideline on this issue.
 
Adam Outler
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's my thinking.

In option 1, every time the DoStuff class is created, then the Log class is also created, meaning load times and higher memory consumption... (my program uses 500 megs of memory). it's easier to program and takes alot of memory.

In option 2, the log class is created and destroyed as needed, leading to possible speedup of certain code and logging operations require the additional step of instatiating a new class. Memory is saved and certain code executes quicker.
 
Adam Outler
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The question really boils down to: Do you "create objects as you need them.", or do you just say "some methods in this class require this object so I'll create it just in case and deal with persistance issues later"?
 
Bear Bibeault
Sheriff
Posts: 67746
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My answer stands: do what makes the most sense and provides the best clarity. Therefore, any solution that contains the phrase "just in case" is naive, and likely suffers from Premature Optimization Syndrome.
 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In your original example the method you are calling is static, so you don't need to create any objects of the Log class. The entire question is moot.

Edit: Wait, sorry, it isn't a static method. You just used a non-standard naming convention which caused me to believe it was. Did somebody already mention readability in this thread?
 
Paul Clapham
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Adam Outler wrote:In option 2, the log class is created and destroyed as needed, leading to possible speedup of certain code and logging operations require the additional step of instatiating a new class. Memory is saved and certain code executes quicker.



No, that's completely wrong. Once a class is loaded, it never gets unloaded. If you had made that statement about objects instead of classes, then some parts of it would be correct. The parts about speedup of code and saving of memory are still just unsupported speculation, though.
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:Edit: Wait, sorry, it isn't a static method. You just used a non-standard naming convention which caused me to believe it was. Did somebody already mention readability in this thread?


Might be static, might not. Log is used as a class name and as a variable name. That might prevent it compiling...although since there are no method return types, and it used New instead of new, it ain't gonna compile anyway :).
 
Paul Clapham
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Adam Outler wrote:my program uses 500 megs of memory.



If your program uses 500 megs then there's no point fussing over the odd logger object here and there. That would be like removing your closet doors so that you had more floor space. (Well, you would. Each door covers about 300 square centimetres of floor space.) Or like removing your front door so that you could get to work faster. (Well, you would. It takes you a couple of seconds to open, close, and lock the door.)

But seriously, if you want to remove memory usage then find out what is using the memory. Don't choose random stuff, profile your code to see what is actually using the memory.
 
Adam Outler
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The code had errors. It's been corrected now. it's usually Log log = new Log().... I wrote it out as an example outside of my editor so it had errors.

Paul Clapham wrote:

Adam Outler wrote:my program uses 500 megs of memory.



If your program uses 500 megs then there's no point fussing over the odd logger object here and there. That would be like removing your closet doors so that you had more floor space. (Well, you would. Each door covers about 300 square centimetres of floor space.) Or like removing your front door so that you could get to work faster. (Well, you would. It takes you a couple of seconds to open, close, and lock the door.)

But seriously, if you want to remove memory usage then find out what is using the memory. Don't choose random stuff, profile your code to see what is actually using the memory.

Ok, I thought I would try to reduce things where i could. That makes sense.

Paul Clapham wrote:

Adam Outler wrote:In option 2, the log class is created and destroyed as needed, leading to possible speedup of certain code and logging operations require the additional step of instatiating a new class. Memory is saved and certain code executes quicker.



No, that's completely wrong. Once a class is loaded, it never gets unloaded. If you had made that statement about objects instead of classes, then some parts of it would be correct. The parts about speedup of code and saving of memory are still just unsupported speculation, though.



So you're saying that the memory manager never cleans up unused classes? how do I destroy them after creation.... Like... I press a button, that launches a method which creates 6 class objects and uses their methods as a separate thread... What then? They just hang around in memory and when I hit the button again another 6 are created?


This is a VERY direct question now.... What's a best practice here? Generate a class object at the highest level for ease of use, or generate a class object at the lowest level possible?
 
Paul Clapham
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Adam Outler wrote:So you're saying that the memory manager never cleans up unused classes? how do I destroy them after creation.... Like... I press a button, that launches a method which creates 6 class objects and uses their methods as a separate thread... What then? They just hang around in memory and when I hit the button again another 6 are created?


This is a VERY direct question now.... What's a best practice here? Generate a class object at the highest level for ease of use, or generate a class object at the lowest level possible?



The best practice, in your case, would be to go back and learn the difference between a class and an object. If you're looking for a very direct answer, that is.

No, the garbage collector doesn't clean up unused classes (which would mean a class for which no instantiated objects exist). That's not a big deal at all because a class takes up very little space. Only a few bytes, maybe 100, I don't know. I have a large and complex system which I run here at work and generally it has about 4,000 classes loaded. That's not enough memory to make a fuss about.

And you don't "generate a class object". You load a class. That happens once, the first time you make a reference to the class. After that you might instantiate an instance of the class -- that would be an object. The garbage collector can remove an object from memory if there are no active references to it, and if it needs the memory it will do that.

Let's take the example you posted. Your code is going to need a logger object at some point. You can create one and keep it around for a while; that uses up some memory. (A logger object wouldn't use much memory, but let's leave that aside for now.) Or you can create one, use it, and let it be garbage collected, and do that a lot. That uses less memory, because that logger object isn't always there, but it makes the garbage collector work harder. So you want to know what's best practice? The answer, as always, is... It depends. Can you afford to spare the memory? (For a logger object, you pretty much always can.) If so, then just create the object and keep it around. If not, then create it for short periods whenever you really need it and then let it be garbage collected. Unless it takes a really long time to create such an object, in which case you have to think about whether you like that. (Note: to create an ordinary object nowadays takes a trivial amount of time. I'm thinking of the case where you might have to get data from a database to create the object, or something like that.)

In other words, if you were looking for a "best practice" which covers everything vaguely like the example you posted, there isn't one. It's actually more complicated than that.
 
Adam Outler
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you. Very insightful. I've read your post twice trying to gain as much knowledge as I can from it. I really appreciate it. Im self taught Java from a schooled background of 3 non-OO programming languages, and extensive use of bash. I will read that a few more times to make sure I got it.

It's not my first time using Java, I have written this last year http://obd-twoner.googlecode.com/svn/trunk/src/ but I'm learning as I go... I'm focused right now on making a cross platform package deployment method called Heimdall One-Click. The package itself is a huge wrapper for binaries and some of my classes take a long time to instantiate so I've moved them to separate threads and processes. http://heimdall-one-click.googlecode.com/svn/trunk/HeimdallOneClick/src/heimdalloneclick/

When it's done it will be a package that deploys the proper binary, deploys the flashable package and then flashes firmware onto a phone using the deployed objects. It looks basically like this http://heimdall-one-click.googlecode.com


Are there any resources which you might suggest?
 
Paul Clapham
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I always recommend the Oracle tutorials: The Java™ Tutorials. When I need to learn a new part of the Java API, that's where I go first.
 
Adam Outler
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i edited the post above right before you posted to give more background and links. nothing major.

Thank you. I've tried reading that and it seems very sparse on content, or maybe it's full on content and I don't understand it.... For example... I tried and tried to learn how to use SwingWorker. I spent two days reviewing the lesson on Concurrency and it did not sink in, so I went looking for videos on "Java Swing Worker" and they're all in Asian languages. Eventually I had to just go with a thread.

Maybe I should just start at the beginning of the tutorials and just keep reading right through the parts that I think I already know.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
. . . yes, and ask about things you don't understand.
 
Paul Clapham
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Usually what I do with those tutorials is, I start with their example code, then I fiddle around with it until I know how to not break it, then I keep on fiddling around until it turns into the code I wanted before I started reading the tutorial. Then I take that code and implement it in the place I wanted to have it.
 
Gravity is a harsh mistress. But this tiny ad is pretty easy to deal with:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic