In performance critical onDraw() method of a View, would it be better to store the instance in a variable and reuse it later or should i just refer my instance as this?
EX:
public class ScheduleListView extends ListView {
private Paint paint = new Paint();
public ScheduleListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
paint.setColor(Color.GRAY);
paint.setAlpha(100);
paint.setColor(Color.parseColor("#47B3EA"));
canvas.drawRect(this.getLeft(), 10, this.getRight(), 10, paint);
super.onDraw(canvas);
canvas.restore();
}
}
the this is referred in this.getRight() and this.getLeft(), would i have any performance improvement if I do the following modification:
private ScheduleListView scheduleListView = this;
... ...
@Override
protected void onDraw(Canvas canvas) {
....
//refer to my instance using scheduleListView instead of this
scheduleListView.getLeft()
....
}
is this good practice? Will this have any performance gain? if not, what is a better way of doing this?
PS: I’m asking this because in jQuery(javascript), if I were to use an object multiple times, I would cache the object in a variable, don’t really know would this be helpful in Java or not….
EX:
var myDiv = $(".myDiv");
myDiv.html();//do stuff
No, that wouldn’t have any improvement.
The most improvement you could make from your code is to move the calls to your paint object to the View’s constructor: