Redis uses a custom struct String called simple dynamic string (SDS ).
The structure is as follows:
struct sdshdr{int len;int free;char buf[];};
The advantages of using such a structure are:
[1] The complexity of length acquisition is O (1), and O (n) is not required );
[2] dynamic allocation of space to avoid buffer overflow and re-allocation of each modification or append;
[3] binary Security;
The first point is obvious. The second point is to reduce the number of times the memory is re-allocated due to modifying the string. redis adopts two measures:
1) pre-allocate space. Assume the following SDS (status [0]) and run the command [sdscat (s, "redis ")] After append a string "redis" to it, the status will change to [1]. What happened? When SDS finds that the current free length cannot be allocated with a new string, a space allocation will occur. If the modified SDS length is less than 1 MB, the total length is [modified length] * 2 + 1, that is, (5 + 5) * 2 + 1, and 1 is the space of the ending symbol. If the total length of SDS after modification is greater than or equal to 1 MB, the length of [modified total length] + 1 MB will be allocated. Assume that the command [sdscat (s, "redis")] is run again. Because the current status [1] Free = 10, there is enough space to allocate new strings, no space allocation operation will occur, and the status will change to [2 ];
Status [0]
struct sdshdr{ int len=5; int free=4; char buf[]={‘h‘,‘e‘,‘l‘,‘l‘,‘o‘,‘\0‘,‘‘,‘‘,‘‘,‘‘}; };
Status [1 ]:
struct sdshdr{ int len=10; int free=10; char buf[]={‘h‘,‘e‘,‘l‘,‘l‘,‘o‘,‘r‘,‘e‘,‘d‘,‘i‘,‘s‘,‘\0‘,...}; };
Status [2 ]:
struct sdshdr{ int len=15; int free=5; char buf[]={‘h‘,‘e‘,‘l‘,‘l‘,‘o‘,‘r‘,‘e‘,‘d‘,‘i‘,‘s‘,‘r‘,‘e‘,‘d‘,‘i‘,‘s‘,‘\0‘,...}; };
2) release the inert space. Now, assume that from the status [2], execute the command [sdstrim (s, "re")] to remove all 'R', 'E ', switch to status [3]. At this time, no space is released, and Len + free is still equal to 20. The purpose of this operation is to avoid re-allocation of memory when the string is shortened, in addition, space is reserved for unfuture string expansion. You can also use [sdsfree] to actually release SDS;
Status [3 ]:
struct sdshdr{ int len=11; int free=9; char buf[]={‘h‘,‘e‘,‘l‘,‘l‘,‘o‘,‘d‘,‘i‘,‘s‘,‘d‘,‘i‘,‘s‘,‘\0‘,...}; };
Third, the Buf attribute of SDS is called a byte array, which stores binary data. Meanwhile, it is safe to use The LEN field to determine whether the string ends, the string will not be truncated because the string is ended with a space.
Redis data structure (I) Simple Dynamic string