Redis study notes (1) String SDS

SDS simple dynamic string.

The structure of SDS:

struct sdshdr{
    
    
	int len;//记录BUF数组中已使用字节的数量 ,等于SDS所八寸字符串的长度
	
	int free;//记录BUF数组中未使用字节的数量
	
	char buf[];//字节数组,用于保存字符串
}

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

2. Prevent buffer overflow. If the c string is not reallocated, the data of the extended string s1 will overflow to the space where s2 is located when the string is spliced, causing the contents of s2 to be accidentally modified (buffer overflow).

3. Prevent memory leaks. If the string is cropped, if the memory is not reallocated, it will cause memory leaks.

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

5. SDS APIs are all binary safe. All SDS APIs will process the data stored in the buf array of SDS in a binary manner. The program will not make any restrictions, filtering, or assumptions on the data, so Redis Instead of using an array to store strings, use it to store a series of binary data.


Learn a little every day, there will always be gains.

Note: Respect the author's intellectual property rights, refer to "Redis Design and Implementation" for the content in the article, and only learn here to share with you.


Insert picture description here

Guess you like

Origin blog.csdn.net/xuetian0546/article/details/106755674