Android Canvas.getClipBounds是否分配Rect对象?
在我的自定义视图中,我正在考虑使用它来优化我的onDraw方法(这样每次调用它时,我只绘制绝对必要的内容) 然而,我仍然想绝对避免任何对象创建 因此,我的问题是:Android Canvas.getClipBounds是否分配Rect对象?,android,optimization,android-canvas,android-custom-view,Android,Optimization,Android Canvas,Android Custom View,在我的自定义视图中,我正在考虑使用它来优化我的onDraw方法(这样每次调用它时,我只绘制绝对必要的内容) 然而,我仍然想绝对避免任何对象创建 因此,我的问题是:getClipBounds()是否每次调用时都分配一个新的Rect?或者它只是简单地循环一个Rect 如果它正在分配一个新对象,我可以通过使用来节省这个开销吗?它似乎使用传递的Rect而不是它自己的Rect (在过早优化之前,请注意,当放置在滚动视图中时,OnDead每秒可调用多次)< P>“GETclipBund())的实际方法声明
getClipBounds()
是否每次调用时都分配一个新的Rect?或者它只是简单地循环一个Rect
如果它正在分配一个新对象,我可以通过使用来节省这个开销吗?它似乎使用传递的Rect而不是它自己的Rect
(在过早优化之前,请注意,当放置在滚动视图中时,OnDead每秒可调用多次)
< P>“GETclipBund())的实际方法声明是“”我已经研究了自Android 4.0.1起Canvas的源代码,如下所示:
/**
* 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;
}
因此,在回答您的问题时,getClipBounds(Rect bounds)将使您免于创建一个对象,但getClipBounds()实际上会在每次调用它时创建一个新的Rect()对象。什么?我不明白。正如我在问题中所写的,有两种不同的方法调用。一个做了一个直肠,一个不做。我问的是一个没有。很抱歉给您带来不便,但是为了避免每次调用该方法时都创建Rect对象,您应该使用这个方法getClipBounds(Rect bounds),正如Luis所说。在我看来,如果您对性能敏感,您可能更喜欢getClipBounds()的简单语义版本不管另一个版本是否进行了一些奇怪的循环优化,这都会采用调用方提供的rect。@DonHatch True。但这确实是问题的一部分——如果备用版本分配或不分配Rect。公认的答案涵盖了这两个问题。请记住,当这个问题写出来时(大约6年前),偷看Android源代码绝非小事。。。