Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

objective c - Pros and Cons of using [NSString stringWithString:@"some string"] versus @"some string"

I want to compare the following simple assignments:

...
@property(nonatomic,retain) UITextField *textField;
...

self.textField.text = @"some string";
self.textField.text = [NSString stringWithString:@"some string"];
self.textField.text = [NSString stringWithFormat:@"some string"];

Where textField is an UITextField and the text property a NSString. Of course all of them work. I know the difference of the last two when using parameters. But lets say we are only interested in this usage.

QUESTIONS:

  1. For doing this kind of assignment, why shouldn't I always use the first one?
  2. Comparing the last two, is there any difference for the compile- and/or runtime of these two? And why should I use stringWithString: at all if not?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Always try to do what feels natural. If you're assigning a constant string then do that, i.e. the first option. @"..." strings are very efficient constants that do not need to be memory managed, so use them if it makes sense.

NSLog(@"%p", @"XX");
NSLog(@"%p", @"XX");
NSLog(@"%p", @"XX");

Results in:

0xa2424
0xa2424
0xa2424

i.e. They are all the same object in memory.

NSLog(@"%p", [NSString stringWithString:@"XX"]);
NSLog(@"%p", @"XX");
NSLog(@"%p", [NSString stringWithString:@"XX"]);

Also results in:

0xa2424
0xa2424
0xa2424

As you can see from this there is no difference between the two objects, thus using -stringWithString: is just an extra message to send. Having said that, the overhead is usually not big enough to make a difference, so it shouldn't be a big deal either way. Personally I'd go with method one as there is no benefit of using method two, it's just extra code.

However,

NSLog(@"%p", [NSString stringWithFormat:@"XX"]);
NSLog(@"%p", [NSString stringWithFormat:@"XX"]);
NSLog(@"%p", [NSString stringWithFormat:@"XX"]);

Results in:

0x7f86730
0xf8479b0
0x8a4cdb0

As you can see, a new string is created each time as the sting you provide is just a format string that is used to process the following substitution variables, as you have none avoid stringWithFormat: unless you need it.

(Obviously all addresses are examples...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...