Redis中保存的key是字符串,value往往是字符串或者是字符串的集合,因此,字符串时Redis中最常用的一种数据结构
但是Redis没有直接使用C语言中的字符串,因为C语言字符串中存在着很多问题:
- 获取字符串长度需要通过运算
- 非二进制安全
- 不可修改
Redis构建了一种新的字符串结构,成为简单动态字符串(Simple Dynamic String),简称SDS。
SDS本质是一个结构体:
struct __attribute__ ((__packed__)) sdshdr8 {
uint8_t len; /* buf已保存的字符串字节数,不包含结束标示*/
uint8_t alloc; /* buf申请的总的字节数,不包含结束标示*/
unsigned char flags; /* 不同SDS的头类型,用来控制SDS的头大小
char buf[];
};
除了长度为8个字节的结构体之外,Redis默认还有其他几种长度的SDS:
/* Note: sdshdr5 is never used, we just access the flags byte directly.
* However is here to document the layout of type 5 SDS strings. */
struct __attribute__ ((__packed__)) sdshdr5 {
unsigned char flags; /* 3 lsb of type, and 5 msb of string length */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr8 {
uint8_t len; /* used */
uint8_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr16 {
uint16_t len; /* used */
uint16_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr32 {
uint32_t len; /* used */
uint32_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr64 {
uint64_t len; /* used */
uint64_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
我们以一个实际例子来看一下,例如,一个包含字符串“addr”的sds结构如下
SDS之所以叫做动态字符串,是因为它具备动态扩容的能力,假如我们要给SDS追加一段字符串“:Beijing”,这里首先会申请新内存空间:
-
如果新字符串小于1M,则新空间为扩展后字符串长度的两倍+1;
-
如果新字符串大于1M,则新空间为扩展后字符串长度+1M+1。称为内存预分配。
优点:
-
获取字符串长度的时间复杂度为O(1)
-
支持动态扩容
-
减少内存分配次数
-
二进制安全