I am curious to know how the OS or compiler manages the memory usage. Take this example of a login screen.
If I enter the same strings for both user ID & password: say "anoop" both times, the following two strings have same addresses:
NSString *userID = self.userNameField.stringValue;
NSString *password = self.passwordField.stringValue;
If I enter "anoop" & "Anoop" respectively, the address changes.
How does the compiler know that the the password text is same as the user ID, so that instead of allocating a new memory space it uses the same reference?
The answer in this case is that you are testing on a 64-bit platform with Objective-C tagged pointers. In this system, some "pointers" are not memory addresses at all; they encode data directly in the pointer value instead.
One kind of tagged pointer on these systems encodes short strings of common characters entirely in the pointer, and "anoop" is a string that can be encoded this way.
Check out Friday Q&A 2015-07-31: Tagged Pointer Strings for a very detailed explanation.
EDIT: see this answer for an explanation of the exact mechanism for short strings on the 64-bit runtime.
Non-mutable NSString instances (well, the concrete immutable subclass instances, as NSString is a class cluster) are uniqued by the NSString class under certain conditions. Even copying such a string will just return itself instead of creating an actual copy.
It may seem strange, but works well in practice, as the semantics of immutable strings allow it: the string cannot change, ever, so a copy of it will forever be indistinguishable from the original string.
Some of the benefits are: smaller memory footprint, less cache thrashing, faster string compares (as two constant strings just need their addresses compared to check for equality).
First of all I want to know, how you checked that. ;-)
However, a user input is done, when the program is executed. At this point in time there is no compiler anymore. So the compiler cannot do any optimization (string matching).
But your Q is broader than your example. And the answer is as in many programming language: If the memory usage is known at compile time ("static", "stack allocated") the compiler generates code that reserves the memory on stack. This applies to local vars.
If the memory usage is not known at compile time, for example if memory is allocated explicitly by the program, the code tells the system to reserve the amount of memory.
来源:https://stackoverflow.com/questions/35801842/why-do-two-nsstrings-taken-from-user-input-end-up-with-the-same-address