开发者

using static constants -- A memory halt?

When we define a variable with following syntax does that mean it is hanging in the memory all the time:

static NSString *const kMyLabel = @"myLabel";

I have 100 of constants. 开发者_StackOverflow社区Should I go with this of #define pre-processor compiler considering that #define will not keep them alive in the memory.


Hardcoded strings, in the format @"my string", are baked into the application binary. In order to make it not be permanent, you'd have to do:

static NSString *kMyLabel = nil;

...somewhere else
kMyLabel = [[NSMutableString alloc] initWithString:@"myLabel"];

But that'd be stupid, because then you'd have both @"myLabel" in memory (because it's part of the app binary) AND your allocated string. So double the memory.

In short:

If you have a constant string, there's no way to "unload" it from memory. And unless you're hard coding a few chapters from a book into your binary, it's not going to be something to worry about. Have you measured it as being a performance issue?


There would be no difference between a constant static variable and #define directive. When using #define, the preprocessor will replace the variable with @"myLabel" every time it is used. This could mean that you have one instance of the string for each use, but the compiler combines them so that any strings in the binary are unique. Using the constant static, the code will load the location of the variable when needed. This means #define may be a tiny bit faster as there is less dereferencing to get the string, but it would be unnoticeable.


It will be "in memory", but it will just be a memory mapped section of your application's executable file. If there's memory pressure, that page will be flushed without writing to disk.

Basically, it's "free" except for a tiny bit of IO on startup. Go nuts with them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜