Redis is written in C language. C-language processing of strings has always been a difficult point. Memory-out-of-bounds issues are prone to occur.
Other high-level languages are easy to implement string stitching, in C here is a difficult one. Because it is necessary to calculate the size of the memory that the string occupies. It cannot be too large (wasting memory), nor too small (out of bounds). This code even appears in a project implemented in the C language.
That is, the size of the string is calculated first. Then request the memory, and then stitch the string.
Such an operation is almost unbearable. Especially when our string composition is more complex, or the string often needs to be changed.
The Redis solution is to use a struct, a set of manipulation functions, to wrap up this complex operation.
In such a string operation, the string calculation no longer occurs. Dynamic memory allocation no longer occurs. All of these operations are included in the SDS operation function.
Redis actually defines a struct:
and SDS in order to be compatible with C-reason char*. The content still ends with a. This is not the same as Nginx's ngx_string.
As a substitute for strlen, SDS also offers Sdslen
The time complexity of the original strlen is O (n), while the time complexity of the Sdslen is O (1)
The memory expansion of SDS, when memory consumption is less than 1M, it will be expanded to twice times the original. In this way, the time complexity of expanding the scale is also O (1). is also highly efficient.
When the memory footprint is more than 1M, it will only grow 1M at a time, no longer twice times the original. You can save memory slightly.
Redis Source Code Analysis SDS, dynamic array