I started learning about redis today. I wanted to see it directly from the source code. However, I saw a basic tutorial on redis, redis design and implementation (first version).
So I decided to start from here.
1. Data Type Definition
typedef char *sds;struct sdshdr { // buf 已占用长度 int len; // buf 剩余可用长度 int free; // 实际保存字符串数据的地方 char buf[];};
2.重新计算新的长度
newlen = sdshdr.len + required_len
if newlen < SDS_MAX_PREALLOC: newlen *= 2 else: newlen += SDS_MAX_PREALLOC
3. 关于这种分配策略会浪费内存吗?
执行 APPEND 命令的字符串键数量通常并不多, 占用内存的体积通常也不大, 所以这一般并不算什么问题
如果执行 APPEND 操作的键很多, 而字符串的体积又很大的话, 那可能就需要修改 Redis 服务器, 让它定时释放一些字符串键的预分配空间, 从而更有效地使用内存。
Summary
- The redis string is expressedSDSInstead of the C string (\ 0EndChar *).
- Compare the C string,SDSIt has the following features:
- You can perform length calculation efficiently (Strlen);
- You can perform the append operation efficiently (Append);
- Binary Security;
- SDSWill be optimized for the append operation: speed up the append operation and reduce the number of memory allocations, at the cost of occupying more memory, and these memories will not be automatically released.
Redis learning-SDS Data Type