There is a structure in ios called TaggedPointer, which is an optimization measure after the device is upgraded from 32-bit to 64-bit. It can greatly reduce the memory usage of small objects, such as NSDate,NSNumber, and NSString

An introduction to the TaggedPointer structure

The TaggedPointer structure here is under LSB, with the tag bit at the end, 8 bytes, 64 bits, as shown in the following figure (MSB is similar to MSB, not to be explained) :

Normally, the storage object points to the content of address + data. Since it is a small object type, change it to the above format of mark + data for direct access (the system also added part of the security processing to encode and decode, which is not considered here).

If the TaggedPoiner type is stored in the TaggedPoiner tagindex, the next three tagindex bits are stored in the TaggedPoiner TaggedPoiner TaggedPoiner TaggedPoiner TaggedPoiner

The payload space is used to store small data, such as ints, bool, floats, dates, and small strings

Note: A taggedPointer is a small pointer that is stored in a pointer, so there is no need to allocate space in the heap. It is a pointer that is passed from object to object, just like a normal number. Retain and release are not required. Release didn’t apply for anything

The taggedPointer structure is relatively simple, so I’ll leave it there

Memory optimization

TaggedPointer shows the importance of bit operations in memory optimization. Here are some common bit operations

Bit operation: the numeric strings in the computer are stored in zeros and ones, and the bit operation is based on them

For example, int a = 12, int a = 12, int a = 12, int a = 12, int a = 12, int a = 12, int a = 12

The basic operations of bit operations

And the corresponding bits on both sides1the1, otherwise,0) 11110101 & 00111010 = 00110000| bitwise or (are corresponding bit1the1, otherwise,0) 11110101 & 00111010 = 11111111~ reverse (0change1.1change0)  11110101 - 00001010<< Arithmetic left shift (same as logical left shift, no sign bits involved)10000111000>> Arithmetic right shift (right shift with sign bit, highest bit supplemented sign bit)11110101 >> 3 = 11111110>>> Logical right shift (unsigned right shift)11110101 >> 3 = 00011110The two are identical0Different a1)  11110101 ^ 00111010 = 11001111Be the same as or be the same as1Different a0, there is no same or sign, we can take the opposite in xor.Copy the code

Swap two data with a shift

Swap a and B, a is equal to1010 0001
b = 0000 1100
a = a^b   //a = 1010 1101 -- 1010 1101 A = a ^ b
b = a^b   //b = 0000 1100 -- 1010 0001 b = a ^ b = a ^ b ^ b = a ^ b
a = a^b   1100 a = a^b = a^b = a^b ^ a = b
Copy the code

The last

Try using bits to do something else (PS: for example, combine the game of Life algorithm for cell survival)