Aleksey
Aleksey

Reputation: 487

Creating more objects rather than perform calculations, how effective?

I have a collection of data (Model) where each element has its visual representation (View) in a form of a JPanel with labels. Here is the method which updates a GUI Page:

public void updateGUIPage(){
    guiPage.removeAll();
    for(MyElement element: myCollection) {
        guiPage.add(new VisualElementWhichExtendsJPanel(element);
        guiPage.add(Box.createVerticalStrut(10);
    }
}

updateGUIPage() is called each time when collection changes. As you see, already created visual elements are removed (as I know from books, they will be later destroyed by Garbage Collector) and new visual elements are created for each element in the collection. I don’t find this way to be very effective, but it simplifies very much application in general (as there are many GUIPages, and many of them show the same element, so if added to second GUIPage it will be removed from the first, that’s the way Swing works) So, the question is: would you allow such approach in your application, or it’s better to make additional calculations and avoid excessive creation of new objects (considering that average size of collection will rarely exceed 100 members)?

Upvotes: 0

Views: 65

Answers (2)

Stephen C
Stephen C

Reputation: 719281

So, the question is: would you allow such approach in your application, or it’s better to make additional calculations and avoid excessive creation of new objects (considering that average size of collection will rarely exceed 100 members)?

The answer to that depends on the relative cost of creating the new objects versus the cost of updating them. And the only way to know for sure what those costs are is the measure them. (And the related question is whether absolute performance "hit" it doing this the slower way is enough to make a real difference ...)

However, this sounds to me like a case of premature optimization. I think you would be better of implementing the application the simpler way, and then seeing how well it performs. If it is too slow, then profile it to determine where the actual performance bottlenecks are. If the profiling tells you that this method is a significant bottleneck, consider doing something about it ... otherwise, leave it alone.

Upvotes: 1

Sergey Nikitin
Sergey Nikitin

Reputation: 116

Completely agree with assylias, my experience with UI development (2+ years with GWT) tells me the same. Go for the simplicity, but make sure to measure performance to see the limits of your approach.

Upvotes: 2

Related Questions