按照通常的short-circuit evaluation question,短路评估对针对nil个对象建立和发送的参数有效吗?例子:

NSMutableArray *nil_array = nil;
....
[nil_array addObject:[NSString stringWithFormat:@"Something big %@",
     function_that_takes_a_lot_of_time_to_compute()]];

是要调用该慢速函数,还是在不处理参数的情况下优化整个addObject的调用?

最佳答案

消息总是分派(dispatch)给对象指针,而不管它是指向对象还是指向nil。另外,消息是在运行时中发送的,因此编译器不能仅仅假设nil_array确实是nil并对其进行优化。如果初始化做了其他事情,并且nil_array变成一个实例怎么办?

这意味着将对您作为方法的参数传递的所有表达式进行求值以便传递,因此不会发生任何形式的短路。您的慢速函数将被执行,如果花费很长时间,它将影响程序的性能。

编辑:我只是为它的内容(空的Objective-C命令行程序)打了一个小测试用例。如果运行此命令并观察调试器控制台,则会注意到出现了所有对function_that_takes_a_lot_of_time_to_compute()的三个调用的输出(以5秒为间隔),而仅出现了t1t3test:方法的输出-自然,因为这些不是nil

main.m

#import "Test.h"

int function_that_takes_a_lot_of_time_to_compute(void)
{
    static int i = 1;

    sleep(5);
    NSLog(@"%d", i);

    return i++;
}

int main(int argc, const char *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    Test *t1 = [[Test alloc] init], *t2 = nil, *t3 = [[Test alloc] init];

    [t1 test:function_that_takes_a_lot_of_time_to_compute()];
    [t2 test:function_that_takes_a_lot_of_time_to_compute()]; // nil
    [t3 test:function_that_takes_a_lot_of_time_to_compute()];

    [t1 release];
    [t3 release];

    [pool drain];
    return 0;
}

Test.h
@interface Test : NSObject {}

- (void)test:(int)arg;

@end

Test.m
@implementation Test

- (void)test:(int)arg
{
    NSLog(@"Testing arg: %d", arg);
}

@end

输出

1个
测试参数:1
2个
3
测试参数:3

关于objective-c - Objective-C是否对所有零个对象的消息都使用短路评估?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4985386/

10-11 22:08
查看更多