Does Canvas.getClipBounds allocate a Rect object?
android, android-canvas, android-custom-view, optimization
Solution
I have looked into the source code for Canvas as of Android 4.0.1, and it is as follows:
/**
* Retrieve the clip bounds, returning true if they are non-empty.
*
* @param bounds Return the clip bounds here. If it is null, ignore it but
* still return true if the current clip is non-empty.
* @return true if the current clip is non-empty.
*/
public boolean getClipBounds(Rect bounds) {
return native_getClipBounds(mNativeCanvas, bounds);
}
/**
* Retrieve the clip bounds.
*
* @return the clip bounds, or [0, 0, 0, 0] if the clip is empty.
*/
public final Rect getClipBounds() {
Rect r = new Rect();
getClipBounds(r);
return r;
}
So, answering your question, getClipBounds(Rect bounds) will spare you from one object creation, but getClipBounds() will actually create a new Rect() object every time it is called.
Problem
In my custom view I'm looking into using Canvas.getClipBounds() to optimize my onDraw method (so that I'm only drawing what's absolutely necessary each time it's called). However, I still want to absolutely avoid any object creation... My question, therefore is: does `getClipBounds()` allocate a new Rect each time it is called? Or is it simply recycling a single Rect? And if it is allocating a new object, can I save this expense by using `getClipBounds(Rect bounds)`, which seems to use the passed Rect instead of its own? (before you scream premature optimization, do consider that when placed in a ScrollView, onDraw can be called many times each second)