儘管Message的構造器是公開的,但是獲取Message對象的最好方法是調用Message.obtain()或者Handler.obtainMessage(), 這樣是從一個可回收對象池中獲取Message對象。
讓我們來看一下Message中obtain的源碼:
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
從全局message pool中獲取一個,比重新分配內存更有效!! /**
* Returns a new {@link android.os.Message Message} from the global message pool.
* More efficient than creating and allocating new instances.
* The retrieved message has its handler set to this instance
* (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
*/
public final Message obtainMessage()
{
return Message.obtain(this);
}
從以上方法可以看出,儘量不要new message兒是從全局message池中obtain會提升性能