1. Redis does not use a C-language string directly (an array of characters ending in a null character), but instead builds a string called Simple dynamic strings, SDS, and SDS as the default string for Redis.
2. Inside the Redis database, the key-value pairs that contain strings are implemented by SDS.
3. For example:
(1) In Redis client execution: Set MSG "HelloWorld", then Redis will create a new key-value pair in the database. The underlying implementation of the key object of a key-value pair is implemented by a SDS that holds the string msg.
The value of a key-value pair is a SDS that holds HelloWorld.
(2) Execution: Set fruit "apple" "Banana" "orange", then the key of the key value pair is an SDS that holds the fruit string.
The value of a key-value pair is a list object, a list object that contains three string objects, and three string objects that are implemented by three SDS, respectively.
4.SDS of the real meaning
(1) The free attribute is 0, indicating that the SDS does not allocate any unused space.
(2) The Len attribute is 5, indicating that the SDS holds a 5-byte long string
(3) The Buf property is an array of type char, the first five bytes of the array are saved, ' R ' e ' d ', and the last byte holds the null character ' s ' (ending with a null character), and the last empty byte is not counted in the Len attribute.
is another example, free is 5, which means that SDS allocates 5 unused byte spaces for BUF.
Spatial optimization Strategy for 5.SDS
(1) Space Pre-distribution
A. When SDS is modified, if the SDS length is less than 1M, then the program allocates unused space of the same size as the Len attribute of the SDS, and the Len attribute value of the SDS will be the same as the free property value.
If the modified SDS Len becomes 13 bytes, then the program will allocate 13 bytes of unused space to the SDS, and the BUF array of SDS has a length of 13+13+1 (end of NULL character) = 27 bytes.
B. If the SDS is longer than 1M after modification to SDS, then the program allocates 1M of unused space to SDS.
If the modified SDS Len becomes 3M, then the length of the BUF is 3m+3m+1byte
with this pre-allocation strategy, the SDS will continuously increase the number of memory redistribution times of n strings, from a certain n to a maximum of N.
(2) Lazy space release strategy
When the SDS-saved string needs to be shortened, the program does not use memory redistribution to reclaim the bytes that have been shortened. Instead, use the free property to record these bytes and wait for future use.
To illustrate:
If the SDS is ABCDEFGHIJ now delete the HIJ, the SDS will be modified to, for example, the free attribute to 3, so that if you want to grow the SDS in the future, you do not need to reallocate the memory space.
Another: SDS provides the appropriate API to free up memory space, so don't worry about memory waste. (Have time to fill in the picture)
REDIS.1--SDS structure