The dynamic string SDS redis

1, Redis an SDS

  Not the same default language string c redis use of default, C language null character, Redis own package, a simple dynamic strings (simple dynamic string, SDS). SDS can be found in the definition of (herein refer to 3.0.0, 3.2.0 will change after) sds.h in the source code, as follows:

1 //sds.h
2 struct sdshdr {
3     unsigned int len;
4     unsigned int free;
5     char buf[];
6 };

The following diagram can be used to explain:

len is 5: 5 indicates that SDS has characters,

free value of 0: indicates that the SDS does not allocate any extra space

buf is an array of char. Len previously stored valid characters.

  SDS also follows the string '\ 0' end of the habit, the final '\ 0' is not counted in the len, entirely by redis function to add their own. Therefore, c can be used as a function to process the buf.

       free value is not 0, '\ 0' position as shown below:

2, SDS comparative advantage and C characters

  • len record length character string length can be acquired by a constant degree of complexity, and the need to obtain normal string after traversing the length thereof.
  • free recording space remaining to avoid buffer overflow. String C language can be directly added, the default assumption that there is extra space can be used, once the assumption does not hold, an overflow occurs.
  • Len free and timely adjustment by provisioning memory, and use the function, when free space enough to avoid re-allocate memory (memory applications is relatively time-consuming operation). When reducing the length of the string do not immediately release the memory.
  • Binary Security: C string null character is considered to have ended, unable to represent some binary data containing null characters in the middle, redis use len record length, but not null character to determine whether the end. redis not just to save the string may be used to store pictures, videos, compressed files and other binary data.

Guess you like

Origin www.cnblogs.com/williamzou/p/12101999.html