Design and implementation of Redis - Achieving data structure (a) String

Redis data structure to achieve (a) a string

       Redis using SDS (simple dynamic string) for strings representing a string value can be modified. Redis used in the key and value.

Note: Redis this type are all key, value different other types, SDS can also be used in the buffer.

Specific defined as follows:

Why not native C string?

  1. Because there STRLEN Redis command, the command may request a key length corresponding to the value (type string must be), if each character string C are required to scan the entire length of the string, less efficient. The SDS and Redis len length attribute is provided, the length can be determined in a time O (1) it is.
  2. When the string concatenation buffer overflow issue exists in C, Redis also has sdscat command, which is used string concatenation, before stitching will first check whether there is enough free, no space is allocated first and then stitching.
  3. Redis need to store binary data, and the string to the C '\ 0' is determined whether it reaches the end, no way to store binary data.

Note: Although their Redis with SDS, but in order to reuse string manipulation functions provided in the C language, or to follow a '\ 0' end of the traditional ~ (len, free this is not the '\ 0' but the actual allocation when the array is allocated in the buff.

SDS Memory redistribution policies?

       Just talked about, if there is not enough free memory will be assigned, we all know, a string of stitching, cutting is very frequent operation, improper memory allocation and recovery will reduce efficiency even bring a memory leak, how it is to optimize the allocation of it?

  1. Pre-allocated space
    1. If len modified less than 1M, it will be allocated in advance, together with the length of the free space equal to len
    2. If len modified 1M or greater, then the space is pre-allocated to 1M
  2. Inert space freed

When cutting the string (string length is reduced), and the space is not immediately released, but remain for the next use. Redis SDS also provides a release of unused memory command ( sdsRemoveFreeSpace command )

   Inert delete code is as follows:

 

      

Published 47 original articles · won praise 8 · views 30000 +

Guess you like

Origin blog.csdn.net/nanchengyu/article/details/89312589