android代码优化的check list

获得Message对象, 尽量使用Handler的obtainMessage(int what), 而不要直接使用new Message()
Message msg = new Message();
msg.what = 1;
msg.arg1 = x;
msg.arg2 = y;

VS:

Handler handler;
Message msg = handler.obtainMessage(1);

Handler.java 源码:

public final Message obtainMessage(int what, Object obj)
{
    return Message.obtain(this, what, obj);
}
Message.java 源码:
public static Message obtain(Handler h, int what, Object obj) {
    Message m = obtain();
    m.target = h;
    m.what = what;
    m.obj = obj;

    return m;
}
/**
* 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里返回一个message对象,避免创建新的对象."
所以为了性能最优, 应该尽量避免直接去new Message().

你可能感兴趣的:(android代码优化的check list)