1

This question is sparked by a response to: Should NSInteger really be used everywhere?

I'm still trying to wrap my head around the implications of using NSInteger for small values, especially now that NSInteger converts to long in a 64-bit environment. I come from the school of thought that says you want to use the smallest possible memory space for maximum efficiency. So, for example, if you know for sure that a variable will only ever hold a value of 0 to 5, then you would use a short, or in the case of Objective-C, int. But you would never use a long because that's just wasteful.

But of course best practice in Objective-C has always been to use NSInteger and NSUInteger, to "future proof" for 64-bit. Now that it's here (referring specifically to iPhone 5S), that small 0 to 5 number that I declared as NSInteger is now being saved in a long 64-bit space.

Maybe it's my lack of a degree, but I'm having a hard time understanding how this is a good thing. Can someone explain it in remedial terms or post a relevant link?

Community
  • 1
  • 1
Justin Whitney
  • 1,242
  • 11
  • 17
  • You seem to be confusing stack and heap allocations when you're thinking about the difference between 32 and 64-bit values. Allocations on the stack are very **fast** and "cheap". Though it's a tired argument, you shouldn't have to worry about stack space running dry because of larger 64-bit values. The iPhone is not an embedded system. – CodaFi Feb 09 '14 at 19:51
  • 2
    Or maybe it's just register allocation that's the problem. MOV'ing a value less than 64-bits wide into a 64-bit register doesn't transform the register, it just sets the bits relevant to that data type (like moving an int into a 64-bit register will set the lower 32 bits, then reading the int means reading the lower 32 bits). You're using the same amount of space, data types just exist to tell the compiler how to read and write values into register space. – CodaFi Feb 09 '14 at 20:07
  • Well now - THAT is beginning to make sense! Specifically the part about the register being 64-bit regardless of the data type. So if I understand correctly, even a `BOOL` is going to be stored in a 64-bit register? – Justin Whitney Feb 09 '14 at 20:30
  • "So, for example, if you know for sure that a variable will only ever hold a value of 0 to 5, then you would use a short, or in the case of Objective-C, int" Why not `short` on Objective-C too? And why not `char` which is even smaller? – user102008 Apr 03 '15 at 22:54

0 Answers0