Design and implementation of redis (a) Simple Dynamic String

redis is implemented in C, but not in the string redis string directly represents the C language, but had built a simple dynamic string type (SDS).

In redis inside, C strings only as a literal, used in some places will not be modified, eg: hit the log.

SDS structure:

struct sdshdr{
  int free;
  int len;
  char buf[];      
}

 

 attribute value of 0 indicates that free unallocated sds unused space.

 len attribute value 5 indicates a string stored sds 5 byte length.

 char buf each byte string type of storage array, and increase "\ 0" at the end of the string.

SDS and C string differences:

1, the length of the string is acquired, C strings need to traverse the string until it finds '\ 0' up, its complexity is O (n), and direct access to SDS len property can get directly length of the string, the complexity of is O (1).

2, SDS's api to prevent buffer overflow, when SDS call SdsCat, will first determine whether the space sds adequate, if not first extended SDS, then string concatenation.

3, in order to reduce the performance impact of reallocation of memory, the string will do increase SDS memory pre-allocation operation, by pre-allocation strategy, the number of allocated memory redis effectively reduced.

. 4, SDS binary safe, C by judging whether the string is '\ 0' to find the end of the string, while the end of the string come through SDS len property, so that the intermediate string has not afraid '\ 0'.

Guess you like

Origin www.cnblogs.com/jasonbourne3/p/11505512.html