The truth is, the compiler can't optimize it away. This
Code: Select all
static unsigned int foo( NSString *s)
{
return( [s length] + [s length] + [s length]);
}
compiles to 100 bytes (and as long as nothing major changes in Objective-C this will always compile into three method calls)
_foo:
000043fc mfspr r0,lr
00004400 bcl 20,31,0x4404
00004404 stmw r27,0xffec(r1)
00004408 mfspr r31,lr
0000440c stw r0,0x8(r1)
00004410 or r27,r3,r3
00004414 addis r29,r31,0x0
00004418 stwu r1,0xffa0(r1)
0000441c addi r29,r29,0x1c08
00004420 lwz r4,0x0(r29)
00004424 bl 0x467c
00004428 lwz r4,0x0(r29)
0000442c or r28,r3,r3
00004430 or r3,r27,r27
00004434 bl 0x467c
00004438 lwz r4,0x0(r29)
0000443c add r28,r28,r3
00004440 or r3,r27,r27
00004444 bl 0x467c
00004448 lwz r0,0x68(r1)
0000444c addi r1,r1,0x60
00004450 add r3,r28,r3
00004454 lmw r27,0xffec(r1)
00004458 mtspr lr,r0
0000445c blr
but
Code: Select all
static unsigned int bar( NSString *s)
{
unsigned int len;
len = [s length];
return( len + len + len);
}
compiles to only 64 bytes
_bar:
00004460 mfspr r0,lr
00004464 stw r31,0xfffc(r1)
00004468 bcl 20,31,0x446c
0000446c stw r0,0x8(r1)
00004470 mfspr r31,lr
00004474 stwu r1,0xffb0(r1)
00004478 addis r4,r31,0x0
0000447c lwz r4,0x1ba0(r4)
00004480 bl 0x467c
00004484 rlwinm r0,r3,1,0,30
00004488 add r3,r0,r3
0000448c lwz r0,0x58(r1)
00004490 addi r1,r1,0x50
00004494 lwz r31,0xfffc(r1)
00004498 mtspr lr,r0
0000449c blr
not only is bar (in my opinion) better style and more readable. It is also faster because the invariant result of the method call is cached and you saved two method calls. Now smaller code size makes for faster programs, because of better cache usage and smaller VM working sets. So you gain even more.
Using local variables as a habit can reduce code size appreciably.