Hi. Let's say I have the following method:

void createNewObject() {
    MyClass myObject = new MyClass();
}

If I call this method 1000 times, how many instances of MyClass will be left in my program's memory by the time all calls have been made? 1000, 1, or 0?
What I'm asking is - can creating new instances of objects inside frequently called methods lead to consequences such as memory leaks (in which case it's better to use a static object)?

You will create 1000 objects, but the only references to them are in the 1000 local variables myObject. Those variables each go out of scope as soon as the method finishes, leaving the object having no references. That makes it eligible for garbage collection, and the garbage collector will destroy the object and free up its memory at a time of its own choosing. If you are short of memory that may be very soon. If you have lots of memory and your code continues to process heavily, then the garbage collection may be deferred for some time, but sooner or later they will all be destroyed.
The question of whether to use a static reference to your object(s) is answered by the functional requirement, not performance. (Objects themselves are not static or instance, they just exist.) Static and instance variables behave differently, and only one will be right for any given task.

Edited 5 Years Ago by JamesCherrill: n/a

This question has already been answered. Start a new discussion instead.