为什么Redis不直接使用C原有字符串

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们都知道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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值