本文介绍了NSString –静态还是内联?有没有性能提升?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

如果我写的话,性能会有所提高

Is there any performance gain if I write

- (NSString *)helloStringWithName:(NSString *)name
    static NSString *formatString = @"Hello %@!";
    return [NSString stringWithFormat:formatString, name];
}

代替

- (NSString *)helloStringWithName:(NSString *)name
    return [NSString stringWithFormat:@"Hello %@!", name];
}

??

如果我猜到了,我会认为每次运行代码时都会创建并自动发布后者,但是我猜编译器足够聪明,可以知道在这里做什么.

If I were to guess I would think that the latter one is created and autoreleased each time the code is running, but I guess the compiler is smart enough to know what do here..

推荐答案

Objective-C中的字符串文字是在编译时分配的,因此,您在性能上不会获得任何好处.

String literals in Objective-C are allocated at compile time, therefore you won't reasonably gain anything in performance.

考虑这个

NSString * str = @"Hello";
NSString * str2 = @"Hello";

NSLog(@"%p", str);  // => 0x860358
NSLog(@"%p", str2); // => 0x860358

因此,如果您的意图是说类似这样的话:

Therefore if your intent is to say something like:

"嘿,编译器,格式字符串始终是相同的,因此不必费心分配多次"

答案将是:

"太好了,告诉我一些我不知道的东西"

注意

如果您仍然持怀疑态度,可以看一下程序集(请查看Dirk的答案),但是让我在这里给您一些建议:不要为此类性能问题而烦恼.

If you are still skeptical you can take a look at the assembly (check out Dirk's answer), but let me give you a piece of advice here: don't bang your head against such performance issues.

使用NSString和高级抽象作为对象的开销通常在程序性能中绝对占主导地位,因此,即使每个字符串获得十亿分之一秒的时间,您也不会合理地注意到这一点.正如您理所当然地怀疑的那样,编译器已经足够聪明,可以处理这些细节.

The overhead of using NSString and a high level abstraction as objects in general is definitely predominant in your program performances, so even if you gain a nanosecond per string, you won't reasonably even notice that.And as you rightfully suspect, the compiler is already smart enough to take care of such details.

总结一下:让编译器完成工作,然后由您完成,即编写可读且可维护的代码.

To wrap it up: let the compiler do its job and you do yours, i.e. writing readable and maintainable code.

这篇关于NSString –静态还是内联?有没有性能提升?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 10:53