------ redis simple dynamic series string (SDS)

Foreword

Redis not directly use conventional string C language representation (null-terminated character array, hereinafter referred to as C string), but had built a simple abstract type named dynamic string (simple dynamic string, SDS) of , and it represents the default string Redis as SDS.

Personal feeling SDS is similar to Java's ArrayList, we can take some of the contrast between the two, whose efficiency is more higher.

 

SDS definitions

. 1  struct sdshdr {
 2  
. 3      // Number of records used in the array buf byte
 4      // is equal to the length of the string stored SDS 
. 5      int len;
 . 6  
. 7      // record the number of unused buf byte array 
. 8      int  Free ;
 . 9  
10      // byte array, for holding the string 
. 11      char buf [];
 12 is  
13 is };

Here note. Char C language is one byte of. Unlike the Java char is two bytes. That is only eight, -127--128.

 

SDS compared to the advantages of the C string

1. Get string length constant complexity

  • This is better understood, there SDS as a len field, the length may be obtained directly

The number of memory reallocation when brought 2. Reduce the modified string

  • Since the conventional string c, is not automatic expansion. And its memory size is equal to the string length +1, and therefore, each time modifying the string, to be re-allocated once memory, a very time-consuming
  • SDS automatically expansion, and can be pre-allocated space. For example, there is now a Hello string. Memory size may be twice Hello, which is 5 * 2 = 10. When the expansion of the string again, when does not necessarily need to allocate memory again. And automatically expansion, assuming 10 enough, after the addition of a string of size 13 , then memory is allocated is 13 = 2 * 26 memory sizes.

3. Binary safe, and you can save an empty character 

  • C string of characters must meet certain coding (such as ASCII), and in addition to the end of the string, the string which can not contain null characters, or the first to be null character program reads will be mistaken for a string end - these limitations make C string can only save the text data, but can not be saved as images, audio, video, compressed files, such as binary data.
  • Thus, the API will in all SDS handles binary processed SDS stored in the  buf array data
  • Everything is stored in the array buf inside, whether English Chinese, audio or images , are binary data stream.

 

Guess you like

Origin www.cnblogs.com/wenbochang/p/11666734.html