Java - Custom paint declaration performance
Quick yes, no, or it doesn't really matter:
I'm overriding the paint method for an abstract button and I'm wondering if doing
GradientPaint gp = new GradientPaint(0, 0, color1, 0, h, color2); RoundRectangle2D r = new RoundRectangle2D.Float(0, 0, w, h, w/5, h/5);
and similar methods are going to affect performance vs
GradientPaint gp; RoundRectangle2D r;
outside paint and then
gp = new GradientPaint(0, 0, color1, 0, h, color2); r = new RoundRectangle2D.Float(0, 0, w, h, w/5, h/5);
inside the paint method
Go for the most maintainable solution until you measure problems :-)
Every "optimization" requires additional logic (aka: LOC). Each additional line has a - difficult to predict - price in maintenance. My general rule it not add uncalculatable costs.
BTW: you can't do your first option anyway, gradients are immutable - so you have to recreate each time the size has changed.
How's it going Jeremy?
Not what you're asking, but quickest of all would likely be to do the drawing once in a BufferedImage, and then display the BufferedImage in the paint (or perhaps better paintComponent) method.
Instantiate them once or when necessary (e.g. size change) rather than many times.