1

I have a confusion regarding programming. What difference does it make in terms of memory if we do this in objective-c:

+(NSString *)getName {
  NSString *name = @"Hello";
  return name;
}

OR

+(NSString *)getName {
  return @"Hello";
}

Is both same or is there any difference in terms of speed and performance?

6
  • 7
    These two, once optimised, should result in the same code. Commented Feb 4, 2014 at 11:51
  • actually i thought that the 1st one will initiate an string object and then store info in it and then return it but the second will not create a string object. Commented Feb 4, 2014 at 11:52
  • 2
    That object is never used or referenced anywhere, so it's going to be removed during optimisation. Commented Feb 4, 2014 at 11:53
  • 6
    As a side note, getters in objective-C are named without 'get'. So your getter would be called -(NSString *)name; Commented Feb 4, 2014 at 11:55
  • You might find these wiki pages interesting: Program Optimization and Optimizing Compiler Commented Feb 4, 2014 at 11:58

1 Answer 1

8

The compiler will optimize the first example into the second example since the variable isn't used for anything else. So they are equivalent: none is faster, none saves any memory.

Edit:

So, I actually tried it and compared the assembler output.

Code used:

@implementation Test

- (NSString *)test1 {
        NSString *variable = @"Hello1";
        return variable;
}

- (NSString *)test2 {
        return @"Hello2";
}

@end

Compiler used:

Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn) Target: x86_64-apple-darwin13.0.0

With no optimization (-O0), test1 does indeed have code for the unused variable (movq %rax, -24(%rbp) and movq -24(%rbp), %rax, so one additional memory write and read). But already at -O1 the variable is optimized away (as are the reads for the internal self and _cmd variables).

So in other words: with -O0 (no optimization), test1 is indeed slower than test2. But if optimizations are switched on, they are equivalent and result in the same code.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for clear me ... :) i thinking that first one create object of string which useless.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.