Redis String Implementation principle SDS

Source: Internet
Author: User
Tags redis

The key in the Redis key-value pair is of type string. What does the Redis internal implementation do with string? The Redis bottom is written in C, for STIRNG does not directly use the C character array, but instead encapsulates a type of SDS. The structure is as follows:

The BUF array is used to store real characters.

Why do you want to create a new data type. It must be for abstraction, and it is easier to program. The original C string API is unsafe because after the use of the character array, it is necessary to track the allocation of memory. Prior to use, pre-allocated space is required, otherwise there will be buffer overflow (of course, the general compiler will use the Canary value to eliminate, compile times a mistake). A string needs to be recycled, otherwise there will be a memory leak.

In order to make programming as little as possible to consider these, it is necessary to put the memory allocation, not let the caller know that this is the role of SDS.

Each time a new string is created, the actual size is not allocated, but more memory is pre-allocated, and when the string is truncated, the memory is not reclaimed immediately, but the Len value is reduced and the free value is increased. When inserting strings, see if free is enough, not enough to redistribute. This reduces the number of memory allocation recoveries and is more efficient. The corresponding strategy is called: space pre-allocation and lazy recycling.

Image above:


Using the SDS data type above, the benefits of programming are three points:

(1) Gets the operation of the length changed to O1.

(2) Elimination of buffer overflow.

(3) Reduce the number of space allocations caused by string changes.

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.