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

来源:互联网 发布:什么软件可以下载图片 编辑:程序博客网 时间:2024/06/09 21:08

尽管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会提升性能

0 0
原创粉丝点击