Is it better (faster & more efficient) to use alloc
or autorelease
initializers. E.g.:
- (NSString *)hello:(NSString *)name {
return [[NSString alloc] initWithFormat:@"Hello, %@", name];
}
OR
- (NSString *)hello:(NSString *)name {
return [NSString stringWithFormat:@"Hello, %@", name];
// return [@"Hello, " stringByAppendingString:name]; // even simpler
}
I know that in most cases, performance here shouldn't matter. But, I'd still like to get in the habit of doing it the better way.
If they do exactly the same thing, then I prefer the latter option because it's shorter to type and more readable.
In Xcode 4.2, is there a way to see what ARC compiles to, i.e., where it puts retain
, release
, autorelease
, etc? This feature would be very useful while switching over to ARC. I know you shouldn't have to think about this stuff, but it'd help me figure out the answer to questions like these.
The difference is subtle, but you should opt for the autorelease
versions. Firstly, your code is much more readable. Secondly, on inspection of the optimized assembly output, the autorelease
version is slightly more optimal.
The autorelease
version,
- (NSString *)hello:(NSString *)name {
return [NSString stringWithFormat:@"Hello, %@", name];
}
translates to
"-[SGCAppDelegate hello:]":
push {r7, lr}
movw r1, :lower16:(L_OBJC_SELECTOR_REFERENCES_-(LPC0_0+4))
mov r3, r2
movt r1, :upper16:(L_OBJC_SELECTOR_REFERENCES_-(LPC0_0+4))
movw r0, :lower16:(L_OBJC_CLASSLIST_REFERENCES_$_-(LPC0_1+4))
movt r0, :upper16:(L_OBJC_CLASSLIST_REFERENCES_$_-(LPC0_1+4))
add r1, pc
add r0, pc
mov r7, sp
ldr r1, [r1]
ldr r0, [r0]
movw r2, :lower16:(L__unnamed_cfstring_-(LPC0_2+4))
movt r2, :upper16:(L__unnamed_cfstring_-(LPC0_2+4))
add r2, pc
blx _objc_msgSend ; stringWithFormat:
pop {r7, pc}
Whereas the [[alloc] init] version looks like the following:
"-[SGCAppDelegate hello:]":
push {r4, r5, r6, r7, lr}
movw r1, :lower16:(L_OBJC_SELECTOR_REFERENCES_2-(LPC1_0+4))
add r7, sp, #12
movt r1, :upper16:(L_OBJC_SELECTOR_REFERENCES_2-(LPC1_0+4))
movw r0, :lower16:(L_OBJC_CLASSLIST_REFERENCES_$_-(LPC1_1+4))
movt r0, :upper16:(L_OBJC_CLASSLIST_REFERENCES_$_-(LPC1_1+4))
add r1, pc
add r0, pc
ldr r5, [r1]
ldr r6, [r0]
mov r0, r2
blx _objc_retain ; ARC retains the name string temporarily
mov r1, r5
mov r4, r0
mov r0, r6
blx _objc_msgSend ; call to alloc
movw r1, :lower16:(L_OBJC_SELECTOR_REFERENCES_4-(LPC1_2+4))
mov r3, r4
movt r1, :upper16:(L_OBJC_SELECTOR_REFERENCES_4-(LPC1_2+4))
add r1, pc
ldr r1, [r1]
movw r2, :lower16:(L__unnamed_cfstring_-(LPC1_3+4))
movt r2, :upper16:(L__unnamed_cfstring_-(LPC1_3+4))
add r2, pc
blx _objc_msgSend ; call to initWithFormat:
mov r5, r0
mov r0, r4
blx _objc_release ; ARC releases the name string
mov r0, r5
pop.w {r4, r5, r6, r7, lr}
b.w _objc_autorelease
As expected, it is a little longer, because it is calling the alloc
and initWithFormat:
methods. What is particularly interesting is ARC is generating sub-optimal code here, as it retains the name
string (noted by call to _objc_retain) and later released after the call to initWithFormat:
.
If we add the __unsafe_unretained
ownership qualifier, as in the following example, the code is rendered optimally. __unsafe_unretained
indicates to the compiler to use primitive (copy pointer) assignment semantics.
- (NSString *)hello:(__unsafe_unretained NSString *)name {
return [[NSString alloc] initWithFormat:@"Hello, %@", name];
}
as follows:
"-[SGCAppDelegate hello:]":
push {r4, r7, lr}
movw r1, :lower16:(L_OBJC_SELECTOR_REFERENCES_2-(LPC1_0+4))
add r7, sp, #4
movt r1, :upper16:(L_OBJC_SELECTOR_REFERENCES_2-(LPC1_0+4))
movw r0, :lower16:(L_OBJC_CLASSLIST_REFERENCES_$_-(LPC1_1+4))
movt r0, :upper16:(L_OBJC_CLASSLIST_REFERENCES_$_-(LPC1_1+4))
add r1, pc
add r0, pc
mov r4, r2
ldr r1, [r1]
ldr r0, [r0]
blx _objc_msgSend
movw r1, :lower16:(L_OBJC_SELECTOR_REFERENCES_4-(LPC1_2+4))
mov r3, r4
movt r1, :upper16:(L_OBJC_SELECTOR_REFERENCES_4-(LPC1_2+4))
add r1, pc
ldr r1, [r1]
movw r2, :lower16:(L__unnamed_cfstring_-(LPC1_3+4))
movt r2, :upper16:(L__unnamed_cfstring_-(LPC1_3+4))
add r2, pc
blx _objc_msgSend
.loc 1 31 1
pop.w {r4, r7, lr}
b.w _objc_autorelease
[NSString stringWithFormat:]
is less code. But be aware that the object may end up in the autorelease pool. And that currently happens even with ARC and -Os compiler optimization.
Currently the performance of [[NSString alloc] initWithFormat:]
is better on both iOS (tested with iOS 5.1.1 and Xcode 4.3.3) and OS X (tested with OS X 10.7.4 and Xcode 4.3.3). I modified @Pascal's sample code to include the autorelease pool drain times and got the following results:
I disagree with the other answers, the autorelease version (your 2nd example) is not necessarily better.
The autorelease version behaves just as is it did before ARC. It allocates and inits and then autoreleases, which means the pointer to the object needs to be stored to be autoreleased later the next time the autorelease pool is drained. This uses slightly more memory as the pointer to that object needs to be kept around until it is processed. The object also sticks around longer than if it was immediately released. This can be an issue if you are calling this many times in a loop so the autorelease pool would not have a chance to be drained. This could cause you to run out of memory.
The first example behaves differently than it did before ARC. With ARC, the compiler will now insert a "release" for you (NOT an autorelease like the 2nd example). It does this at the end of the block where the memory is allocated. Usually this is at the end of the function where it is called. In your example, from viewing the assembly, it seems like the object may in fact be autoreleased. This might be due to the fact the compiler doesn't know where the function returns to and thus where the end of the block is. In the majority of the cases where a release is added by the compiler at the end of a block, the alloc/init method will result in better performance, at least in terms of memory usage, just as it did before ARC.
Well, this is something easy to test, and indeed it seems the convenience constructor is "faster" -- unless I made some error in my test code, see below.
Output (Time for 1 Million constructions)
Alloc/init: 842.549473 millisec
Convenience: 741.611933 millisec
Alloc/init: 799.667462 millisec
Convenience: 741.814478 millisec
Alloc/init: 821.125221 millisec
Convenience: 741.376502 millisec
Alloc/init: 811.214693 millisec
Convenience: 795.786457 millisec
Script
#import <Foundation/Foundation.h>
#import <mach/mach_time.h>
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSUInteger runs = 4;
mach_timebase_info_data_t timebase;
mach_timebase_info(&timebase);
double ticksToNanoseconds = (double)timebase.numer / timebase.denom;
NSString *format = @"Hello %@";
NSString *world = @"World";
NSUInteger t = 0;
for (; t < 2*runs; t++) {
uint64_t start = mach_absolute_time();
NSUInteger i = 0;
for (; i < 1000000; i++) {
if (0 == t % 2) { // alloc/init
NSString *string = [[NSString alloc] initWithFormat:format, world];
}
else { // convenience
NSString *string = [NSString stringWithFormat:format, world];
}
}
uint64_t run = mach_absolute_time() - start;
double runTime = run * ticksToNanoseconds;
if (0 == t % 2) {
NSLog(@"Alloc/init: %.6f millisec", runTime / 1000000);
}
else {
NSLog(@"Convenience: %.6f millisec", runTime / 1000000);
}
}
}
return 0;
}
Comparing the performance of the two is a bit of a moot issue for a couple of reasons. First, the performance characteristics of the two might change as Clang evolves, and new optimisations are added to the compiler. Second, the benefits of skipping a few instructions here and there are dubious at best. The performance of your app should be considered across method boundaries. Deconstructing one method can be deceiving.
I think that the stringWithFormat: implementation is actually implemented just as your 1st version, which means nothing should change. In any case, if there is any difference, it probably seems as the second version should not be slower. Finally, in my opinion the second version is slightly more readable, so that's what I'd use.