Redis Source Code Analysis SDS, dynamic array

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.