Android中创建Message两种方法比较,new Message和obtainMessage

尽管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中获取一个,比重新分配内存更有效!!


Handler.obtainMessage()方法的使用!

 /**
     * 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会提升性能

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章