Redis learning notes (I) string SDS


SDS simple dynamic string.

SDS structure:

struct sdshdr{
int len;// Record the number of bytes used in the buf array, which is equal to the length of the eight inch string required by SDS

int free;// Records the number of unused bytes in the buf array

char buf[];// Byte array to hold string

1. Compared with the string of C language, when SDS obtains the length, the time complexity bit is O (1), and the complexity bit of C is O (n).

2. Eliminate buffer overflow. If the memory of C string is not reallocated, the data of extended string S1 will overflow to the space of S2 during string splicing, resulting in unexpected modification of the content saved by S2 (buffer overflow).

3. Eliminate memory leakage. If the string is cropped and the memory is not reallocated, it will cause memory leakage.

4. For SDS, if it is extended, the SDS API will check whether the space is sufficient. If it is sufficient, the unused space will be used directly without reallocation. Inert free space. When SDS needs to be shortened, the program will not immediately reallocate memory, but use free to record these excess space for future use.

5. All SDS APIs use binary security. All SDS APIs process the data stored in the buf array in the way of binary processing. The program will not make any restrictions, filters or assumptions on the data. Therefore, redis does not use the array to save strings, but uses it to save a series of binary data.