Redis源码初识二 字符串数据结构

sds

名称:简单动态字符串(simple dynamic string,SDS )
所有数据类型中都有用到此数据结构
所有类型的key,都是此类型数据结构

sds.h(源码)

struct __attribute__ ((__packed__)) sdshdr5 {
    unsigned char flags; /* 3 lsb of type, and 5 msb of string length */
    char buf[];// buf[0]: z:  0101001
};
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[];
};

sds存储结构如图

在这里插入图片描述

字段含义

flags
第三位:记录字符串类型(sdshdr5、sdshdr8、sdshdr16、sdshdr32、sdshdr64)
高五位:记录字符串占用字节数(最高表示31个长度 2^5-1)
buf[]
实际存的字符串的每个字符数据的数组
len
记录字符串长度,buf使用长度
alloc
buf总长度,包含未分配内存

总结

  1. 当字符串长度小于等于31时,使用sdshdr5,只使用flags,字符串长度使用高五位记录
  2. 当字符串长度大于31,并且小于2^8-1(255)时,使用sdshdr8,flgas高五位不记录数据,使用len和alloc记录字符串长度和预分配长度(各占用1个byte)
  3. 当字符串长度大于254,并且小于2^16-1(65535)时,使用sdshdr16,flgas高五位不记录数据,使用len和alloc记录字符串长度和预分配长度(各占用2个byte)
  4. redis的sds会自动在结尾拼上\0,使其支持部分c语言字符串函数

redis为什么使用sds而不使用c语言自带的字符串:

  1. c语音以\0表示结尾,如果字符串中间包含\0,c语言会识别错误
  2. c语言没有记录字符串长度,每次统计字符串需要遍历,时间复杂度o(n),sds使其时间复杂度变为o(1)
  3. c语言拼接字符串,每次都需要申请内存空间(比较耗时),sds会使用预分配方式,如果下次拼接时,剩余空间够,不需要申请内存,直接可以使用
    • 修改后sds长度(len)小于1mb,预分配空间与len长度相同,实际sds的buf数组长度为(len+len+1byte)
    • 修改后sds长度(len)大于1mb,预分配空间为1mb,实际sds的buf数组长度为(len+1mb+1byte)
  4. sds会已\0结尾,兼容部分c字符串函数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值