The key in the Redis key-value pair is of type string. What does the Redis internal implementation do with string? The Redis bottom is written in C, for STIRNG does not directly use the C character array, but instead encapsulates a type of SDS. The structure is as follows:
The BUF array is used to store real characters.
Why do you want to create a new data type. It must be for abstraction, and it is easier to program. The original C string API is unsafe because after the use of the character array, it is necessary to track the allocation of memory. Prior to use, pre-allocated space is required, otherwise there will be buffer overflow (of course, the general compiler will use the Canary value to eliminate, compile times a mistake). A string needs to be recycled, otherwise there will be a memory leak.
In order to make programming as little as possible to consider these, it is necessary to put the memory allocation, not let the caller know that this is the role of SDS.
Each time a new string is created, the actual size is not allocated, but more memory is pre-allocated, and when the string is truncated, the memory is not reclaimed immediately, but the Len value is reduced and the free value is increased. When inserting strings, see if free is enough, not enough to redistribute. This reduces the number of memory allocation recoveries and is more efficient. The corresponding strategy is called: space pre-allocation and lazy recycling.
Image above:
Using the SDS data type above, the benefits of programming are three points:
(1) Gets the operation of the length changed to O1.
(2) Elimination of buffer overflow.
(3) Reduce the number of space allocations caused by string changes.