preface

NSNumber *num = @(20); I only need to store 20.

In a normal technical scheme, on a 64-bit CPU, you would create an NSNumber object with a value of 20, followed by a pointer num to that address. There was no problem, but it was a waste.

  • Memory is a waste of

Due to memory alignment in OC, at 64-bit, an object is created with at least 16 bytes, plus a pointer with 8 bytes, for a total of 24 bytes. In other words, the need for 24 bytes to store this 20 is a huge waste of memory.

  • Performance of the waste

To store and access an NSNumber object, you need to allocate memory for it on the heap, maintain its reference count, and manage its lifetime. All this adds extra logic to the program, resulting in a loss of efficiency.

Tagged Pointer technology

To solve this problem, Apple introduced the concept of Tagged Pointer.

Starting from 64-bit, iOS introduces Tagged Pointer technology to optimize storage of small objects such as NSNumber, NSDate, and NSString. When introduced, correlation logic can reduce memory usage by half, increase access speed by 3 times, and increase creation and destruction speed by 100 times.

  • The principle of

Store data directly in Pointers. When Pointers are insufficient to store data, dynamically allocated memory is used to store data.

After using Tagged Pointer, the Data stored in the NSNumber Pointer becomes Tag + Data,

The objc_msgSend() function can recognize Tagged Pointer, such as the intValue method of NSNumber, and extract data directly from the Pointer, saving the overhead of previous calls.

Previously, objects such as NSNumber needed to allocate memory dynamically and maintain reference counting, etc., and the NSNumber pointer stored the address value of the NSNumber object in the heap.