iOS 性能OC 底层

ARC与MRC性能对比

2019-03-12  本文已影响0人  介和

参考 http://www.cocoachina.com/ios/20150817/13077.html

ARC is generally faster, and ARC can indeed be slower

嗯,有些矛盾。不过在文章中,Steffen Itterheim指出大部分情况下,ARC的性能是更好的,这主要得益于一些底层的优化以及autorelease pool的优化,这个从官方文档也能看到。但在一些情况下,ARC确实是更慢,ARC会发送一些额外的retain/release消息,如一些涉及到临时变量的地方,看下面这段代码:

// this is typical MRC code:

{

    id object = [array objectAtIndex:0];

    [object doSomething];

    [object doAnotherThing];

}

// this is what ARC does (and what is considered best practice under MRC):

{

    id object = [array objectAtIndex:0];

    [object retain]; // inserted by ARC

    [object doSomething];

    [object doAnotherThing];

    [object release]; // inserted by ARC

}

另外,在带对象参数的方法中,也有类似的操作:

// this is typical MRC code:

-(void) someMethod:(id)object

{

    [object doSomething];

    [object doAnotherThing];

}

// this is what ARC does (and what is considered best practice under MRC):

-(void) someMethod:(id)object

{

    [object retain]; // inserted by ARC

    [object doSomething];

    [object doAnotherThing];

    [object release]; // inserted by ARC

}

  这些些额外的retain/release操作也成了降低ARC环境下程序性能的罪魁祸首。但实际上,之所以添加这些额外的retain/release操作,是为了保证代码运行的正确性。如果只是在单线程中执行这些操作,可能确实没必要添加这些额外的操作。但一旦涉及以多线程的操作,问题就来了。如上面的方法中,object完全有可能在doSoming和doAnotherThing方法调用之间被释放。为了避免这种情况的发生,便在方法开始处添加了[object retain],而在方法结束后,添加了[object release]操作。

上一篇下一篇

猜你喜欢

热点阅读