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...)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…