我们都知道Redis没有直接使用C原有的字符串而是自己构建了"简单动态字符串"(simple dynamic String)简单SDS.
我们可以先看下对于sds结构体
sds结构在3.0和之后的版本(3.2开始有所不同)
Redis 3.0版本(包含之前)
/*
* len : 字符串长度/字符数组中已使用的字符数量
* free : 字符数组中未被使用的字符数量
* buf : 字符数组,用来保存字符串
*/
struct sdshdr {
unsigned int len;
unsigned int free;
char buf[];
};
3.2 版本
/*
1. len : 字符串长度/字符数组中已使用的字符数量
2. alloc: 字符串已分配字节数,不同于free,记录的是为buf分配的总长度
3. flags:标识当前结构体的类型(0~4)
4. buf : 字符数组,用来保存字符串
*/
/* Note: sdshdr5 is never used, we just access the flags byte directly.
5. 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

Redis为了解决C字符串的若干问题,如长度获取、缓冲区溢出、频繁内存分配等,自定义了简单动态字符串(SDS)。SDS在3.2版本后增加了更多类型,并提供优势,如快速获取长度、避免溢出、优化内存操作,同时仍能兼容C字符串函数。
最低0.47元/天 解锁文章
1087

被折叠的 条评论
为什么被折叠?



