Why do two NSStrings taken from user input end up with the same address?

蹲街弑〆低调 提交于 2019-12-06 15:04:36
rob mayoff

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.

dognotdog

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!