2

我有一个AppSettingsController用几个方法命名的单例类。

一般来说,我这样称呼他们:

[[AppSettingsController sharedInstance] myMethod];

这很好。

这是创建实例的方式:

+ (id)sharedInstance
{
    static AppSettingsController *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

但我正在考虑别的事情。假设我必须循环调用 myMethod 。创建这个单例的局部变量并用这个变量调用这个方法不是更好吗?

AppSettingsController *mySharedInstance = [AppSettingsController sharedInstance];
loop
  [mySharedInstance myMethod];

...而不是直接调用它?

loop
  [[AppSettingsController sharedInstance] myMethod];

哪种方式更有效或两者相等?

4

4 回答 4

3

[[AppSettingsController sharedInstance] myMethod];代码将循环调用两个方法

AppSettingsController *mySharedInstance = [AppSettingsController sharedInstance];
循环
[mySharedInstance myMethod];

只会打电话给一个

在第二种情况下,您正在保存单个方法调用,因此第二种更有效。此外,如果在您的sharedInstance方法中您说4了更多方法调用和一些初始化语句,那么在这种情况下,您也将保存调用和初始化语句。


更新

编写 sudo 汇编代码(使用 Sudo 汇编器:P)。只需了解这个想法,不要使用确切的汇编代码

Case 1:
Loop start:
1 Call method sharedInstance

  [this code step 2-7 will be called only once]
  2 Create a static AppSettingsController *sharedInstance = nil; in sharedInstance method
  3 Create static dispatch_once_t onceToken;
  4 Call dispatch_once
  5 Now dispatch_once takes lock of onceToken (and other task which is not visible for me)
  6 Call [self alloc]
  7 Call [self init]

8 Return from sharedInstance
9 Call myMethod
Loop ends:




Case 2:
1 Call method sharedInstance
2 Create a static AppSettingsController *sharedInstance = nil; in sharedInstance method
3 Create static dispatch_once_t onceToken;
4 Call dispatch_once
5 Now dispatch_once takes lock of onceToken (and other task which is not visible for me)
6 Call [self alloc]
7 Call [self init]
8 Return from sharedInstance
9 Assign sharedInstance value to mySharedInstance variable
Loop starts:
10 Call myMethod
Loop Ends:

在这里你可以清楚地看到你在保存什么

于 2013-02-21T14:32:02.767 回答
2

恕我直言,对于大多数情况,这是一个理论上的讨论——当每次在循环中访问 sharedInstance 而不是在循环之前设置局部变量时只访问一次时,您不会感受到更多一级间接的性能影响。

使用您最喜欢的版本(可读性),或者如果您确实关心性能损失,请使用局部变量方式。

于 2013-02-21T15:22:04.183 回答
1

在我看来,你做的第一件事更好:

[[AppSettingsController sharedInstance] myMethod];

它是一个单例,因为它不需要实例。所以,第一种方法更好。我认为创建一个实例可能比直接调用使用更多的内存,但我不确定这一点。

于 2013-02-21T14:29:51.953 回答
1

去打第二个电话

[[AppSettingsController sharedInstance] myMethod];

因为这种方式被世界使用并且更具可读性。

于 2013-02-21T14:33:39.497 回答