Redis 資料結構-簡單動態字串
無邊落木蕭蕭下,不盡長江滾滾來,
1、簡介
Redis 之所以快主要得益于它的資料結構、操作記憶體資料庫、單執行緒和多路 I/O 復用模型,進一步窺探下它常見的五種基本資料的底層資料結構,
Redis 常見資料型別對應的的底層資料結構,
- String:簡單動態字串,
- List:雙向鏈表、壓縮串列,
- Hash:壓縮串列、哈希表,
- Sorted Set:壓縮串列、跳表,
- Set:哈希表、整數陣列,

2、簡單動態字串
String是Redis 最基本的型別,最大能存盤 512MB 的資料,String型別是二進制安全的,它可以存盤任何資料包括數字、圖片、序列化物件等,雖然Redis 是C 語言寫的,但Redis 中并沒有使用 C 中 char 來表示字串,而是自定義了一種新的字串結構 簡單動態字串(Simple Dynamic Strings,SDS)來存盤字串和整型資料,
C 語言字串有以下幾個問題:
- C 中獲取字串長度的需要通過運算,復雜度為O(n),
- 非二進制安全,不能出現類似于’\0’的字符,因為在C 字串中,'\0’代表字串結束,
- 每一次洗掉和增加字串的長度,都需要重新分配空間,
SDS 結構
例如執行以下命令
set name "tjt"

set命令執行后,Redis將在底層創建兩個SDS,一個是包含name 的SDS,另一個是包含“tjt”的SDS,
從Redis 原始碼的sds.h 檔案中可以看到SDS 的結構體,

從sds.h 原始碼中截取出sdshdr8 如下,
1 struct __attribute__ ((__packed__)) sdshdr8 { 2 uint8_t len; /* used */ 3 uint8_t alloc; /* excluding the header and null terminator */ 4 unsigned char flags; /* 3 lsb of type, 5 unused bits */ 5 char buf[]; 6 };
- len: 記錄 char buf [] 陣列中已使用位元組的數量,等于 SDS 保存字串的長度,不包含結束識別符號'\0'
- alloc:記錄 char buf [] 陣列申請的總位元組數,不包含結束識別符號'\0'
- buf:位元組陣列,用戶保存字串
- flags:不同SDS 頭型別,sds 會根據字串實際的長度,選擇不同的資料結構,節省記憶體空間,更好的提升記憶體效率,當前 sdshdr 結構分為 5 種子型別,分別為
sdshdr5、sdshdr8、sdshdr16、sdshdr32、sdshdr64,如下圖對應的幾種SDS_TYPE,

例如,一個包含字串“tjt"的SDS 結構如下:

動態字串SDS 具備動態擴容的能力,例如給SDS 'tjt' 追加一段字串 ",go”,這里首先會申請新記憶體空間,
- 如果新字串小于1M,則新空間為 擴展后字串長度的兩倍 + 1;
- 如果新字串大于1M,則新空間為 擴展后字串長度 + 1M +1 ,空間預分配用于優化 SDS 的字串增長操作,

3、Redis 使用SDS 的優勢
1、SDS可以通過常數級別獲取字串的長度
redis的結構中存盤了字串的長度,所以獲取字串的長度復雜度為O(1),c 中字串沒記錄長度,需要遍歷整個長度,復雜度為O(N),
2、杜絕緩沖區溢位
- 如果在修改字符的時候,沒有分配足夠的記憶體大小,就很容易造成快取溢位,記憶體越界,
- strcat 函式常見的錯誤就是陣列越界,即兩個字串連接后,長度超過第一個字串陣列定義的長度,導致越界,
- SDS 中的空間分配策略可以杜絕這種情況,當對 SDS 進行修改時,API 會檢查 SDS 的空間是否滿足修改所需的要求,如果不滿足的話,API 會自動將 SDS 的空間擴展至執行修改所需的大小,然后才執行實際的修改操作,空間的申請是自動完成的,所以就避免了快取溢位,
3、減少修改字串時的記憶體分配次數
- 對于 C 字串來說,如果修改字串的長度,都需要重新執行記憶體分配操作;但是對于 Redis 資料庫來說,如果頻繁執行記憶體分配/釋放操作,必然會對性能產生一定影響,為了避免 C 字串的缺陷,SDS 采用了空間預分配和惰性空間釋放兩種優化策略,
- 空間預分配:redis分配的空間不是按照需要的分配,一般會有多余的空間,所以字串長度增加時,剩余的空間足夠,就可以避免重新分配空間,減少修改字串時的空間分配次數,
- 惰性釋放:減少字符的長度時也不是直接洗掉多余的內容,而是設定已使用空間的長度,隱藏洗掉內容,
4、二進制安全
- 對于 C 字串來說,字串中不能包含空字符,否則最先被程式讀入的空字串被誤認為是字串結尾,這使得 C 字串只能保存文本資料,而不能保存圖片、音視頻等二進制檔案,
- 對于 SDS 來說,采用二進制存盤,所有 SDS 都會以處理二進制的方式來處理 SDS 保存在 buf 陣列中的內容,程式不會對里面的內容做任何限制,
5、Int、Raw和 embstr 動態存盤
簡單動態字串結構在資料存盤程序中,字串物件會根據保存值的型別、長度不同,動態匹配三種存盤結構:Int、Raw和 embstr ,
- Int:如果存盤的是整數值(可以用long表示),則底層存盤結構為Int;
- raw:如果存盤的是字串且字串長度超過39 位元組,則底層存盤結構為raw;
- embstr:如果存盤的是字串且字串長度未超過39 位元組,則底層存盤結構為embstr(需要一塊連續的記憶體空間);
- embstr 和raw 都使用redisObject 和sdshdr 結構來表示字串物件,但是raw 會分別兩次創建redisObject 與sdshdr,記憶體不一定是連續的,而embstr 直接創建一塊連續的記憶體,embstr 是一塊連續的記憶體空間,因此其效率上比raw 方式要高,

sds.h 檔案完整原始碼
1 /* SDSLib 2.0 -- A C dynamic strings library 2 * 3 * Copyright (c) 2006-2015, Salvatore Sanfilippo <antirez at gmail dot com> 4 * Copyright (c) 2015, Oran Agra 5 * Copyright (c) 2015, Redis Labs, Inc 6 * All rights reserved. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions are met: 10 * 11 * * Redistributions of source code must retain the above copyright notice, 12 * this list of conditions and the following disclaimer. 13 * * Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * * Neither the name of Redis nor the names of its contributors may be used 17 * to endorse or promote products derived from this software without 18 * specific prior written permission. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 * POSSIBILITY OF SUCH DAMAGE. 31 */ 32 33 #ifndef __SDS_H 34 #define __SDS_H 35 36 #define SDS_MAX_PREALLOC (1024*1024) 37 const char *SDS_NOINIT; 38 39 #include <sys/types.h> 40 #include <stdarg.h> 41 #include <stdint.h> 42 43 typedef char *sds; 44 45 /* Note: sdshdr5 is never used, we just access the flags byte directly. 46 * However is here to document the layout of type 5 SDS strings. */ 47 struct __attribute__ ((__packed__)) sdshdr5 { 48 unsigned char flags; /* 3 lsb of type, and 5 msb of string length */ 49 char buf[]; 50 }; 51 struct __attribute__ ((__packed__)) sdshdr8 { 52 uint8_t len; /* used */ 53 uint8_t alloc; /* excluding the header and null terminator */ 54 unsigned char flags; /* 3 lsb of type, 5 unused bits */ 55 char buf[]; 56 }; 57 struct __attribute__ ((__packed__)) sdshdr16 { 58 uint16_t len; /* used */ 59 uint16_t alloc; /* excluding the header and null terminator */ 60 unsigned char flags; /* 3 lsb of type, 5 unused bits */ 61 char buf[]; 62 }; 63 struct __attribute__ ((__packed__)) sdshdr32 { 64 uint32_t len; /* used */ 65 uint32_t alloc; /* excluding the header and null terminator */ 66 unsigned char flags; /* 3 lsb of type, 5 unused bits */ 67 char buf[]; 68 }; 69 struct __attribute__ ((__packed__)) sdshdr64 { 70 uint64_t len; /* used */ 71 uint64_t alloc; /* excluding the header and null terminator */ 72 unsigned char flags; /* 3 lsb of type, 5 unused bits */ 73 char buf[]; 74 }; 75 76 #define SDS_TYPE_5 0 77 #define SDS_TYPE_8 1 78 #define SDS_TYPE_16 2 79 #define SDS_TYPE_32 3 80 #define SDS_TYPE_64 4 81 #define SDS_TYPE_MASK 7 82 #define SDS_TYPE_BITS 3 83 #define SDS_HDR_VAR(T,s) struct sdshdr##T *sh = (void*)((s)-(sizeof(struct sdshdr##T))); 84 #define SDS_HDR(T,s) ((struct sdshdr##T *)((s)-(sizeof(struct sdshdr##T)))) 85 #define SDS_TYPE_5_LEN(f) ((f)>>SDS_TYPE_BITS) 86 87 static inline size_t sdslen(const sds s) { 88 unsigned char flags = s[-1]; 89 switch(flags&SDS_TYPE_MASK) { 90 case SDS_TYPE_5: 91 return SDS_TYPE_5_LEN(flags); 92 case SDS_TYPE_8: 93 return SDS_HDR(8,s)->len; 94 case SDS_TYPE_16: 95 return SDS_HDR(16,s)->len; 96 case SDS_TYPE_32: 97 return SDS_HDR(32,s)->len; 98 case SDS_TYPE_64: 99 return SDS_HDR(64,s)->len; 100 } 101 return 0; 102 } 103 104 static inline size_t sdsavail(const sds s) { 105 unsigned char flags = s[-1]; 106 switch(flags&SDS_TYPE_MASK) { 107 case SDS_TYPE_5: { 108 return 0; 109 } 110 case SDS_TYPE_8: { 111 SDS_HDR_VAR(8,s); 112 return sh->alloc - sh->len; 113 } 114 case SDS_TYPE_16: { 115 SDS_HDR_VAR(16,s); 116 return sh->alloc - sh->len; 117 } 118 case SDS_TYPE_32: { 119 SDS_HDR_VAR(32,s); 120 return sh->alloc - sh->len; 121 } 122 case SDS_TYPE_64: { 123 SDS_HDR_VAR(64,s); 124 return sh->alloc - sh->len; 125 } 126 } 127 return 0; 128 } 129 130 static inline void sdssetlen(sds s, size_t newlen) { 131 unsigned char flags = s[-1]; 132 switch(flags&SDS_TYPE_MASK) { 133 case SDS_TYPE_5: 134 { 135 unsigned char *fp = ((unsigned char*)s)-1; 136 *fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS); 137 } 138 break; 139 case SDS_TYPE_8: 140 SDS_HDR(8,s)->len = newlen; 141 break; 142 case SDS_TYPE_16: 143 SDS_HDR(16,s)->len = newlen; 144 break; 145 case SDS_TYPE_32: 146 SDS_HDR(32,s)->len = newlen; 147 break; 148 case SDS_TYPE_64: 149 SDS_HDR(64,s)->len = newlen; 150 break; 151 } 152 } 153 154 static inline void sdsinclen(sds s, size_t inc) { 155 unsigned char flags = s[-1]; 156 switch(flags&SDS_TYPE_MASK) { 157 case SDS_TYPE_5: 158 { 159 unsigned char *fp = ((unsigned char*)s)-1; 160 unsigned char newlen = SDS_TYPE_5_LEN(flags)+inc; 161 *fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS); 162 } 163 break; 164 case SDS_TYPE_8: 165 SDS_HDR(8,s)->len += inc; 166 break; 167 case SDS_TYPE_16: 168 SDS_HDR(16,s)->len += inc; 169 break; 170 case SDS_TYPE_32: 171 SDS_HDR(32,s)->len += inc; 172 break; 173 case SDS_TYPE_64: 174 SDS_HDR(64,s)->len += inc; 175 break; 176 } 177 } 178 179 /* sdsalloc() = sdsavail() + sdslen() */ 180 static inline size_t sdsalloc(const sds s) { 181 unsigned char flags = s[-1]; 182 switch(flags&SDS_TYPE_MASK) { 183 case SDS_TYPE_5: 184 return SDS_TYPE_5_LEN(flags); 185 case SDS_TYPE_8: 186 return SDS_HDR(8,s)->alloc; 187 case SDS_TYPE_16: 188 return SDS_HDR(16,s)->alloc; 189 case SDS_TYPE_32: 190 return SDS_HDR(32,s)->alloc; 191 case SDS_TYPE_64: 192 return SDS_HDR(64,s)->alloc; 193 } 194 return 0; 195 } 196 197 static inline void sdssetalloc(sds s, size_t newlen) { 198 unsigned char flags = s[-1]; 199 switch(flags&SDS_TYPE_MASK) { 200 case SDS_TYPE_5: 201 /* Nothing to do, this type has no total allocation info. */ 202 break; 203 case SDS_TYPE_8: 204 SDS_HDR(8,s)->alloc = newlen; 205 break; 206 case SDS_TYPE_16: 207 SDS_HDR(16,s)->alloc = newlen; 208 break; 209 case SDS_TYPE_32: 210 SDS_HDR(32,s)->alloc = newlen; 211 break; 212 case SDS_TYPE_64: 213 SDS_HDR(64,s)->alloc = newlen; 214 break; 215 } 216 } 217 218 sds sdsnewlen(const void *init, size_t initlen); 219 sds sdsnew(const char *init); 220 sds sdsempty(void); 221 sds sdsdup(const sds s); 222 void sdsfree(sds s); 223 sds sdsgrowzero(sds s, size_t len); 224 sds sdscatlen(sds s, const void *t, size_t len); 225 sds sdscat(sds s, const char *t); 226 sds sdscatsds(sds s, const sds t); 227 sds sdscpylen(sds s, const char *t, size_t len); 228 sds sdscpy(sds s, const char *t); 229 230 sds sdscatvprintf(sds s, const char *fmt, va_list ap); 231 #ifdef __GNUC__ 232 sds sdscatprintf(sds s, const char *fmt, ...) 233 __attribute__((format(printf, 2, 3))); 234 #else 235 sds sdscatprintf(sds s, const char *fmt, ...); 236 #endif 237 238 sds sdscatfmt(sds s, char const *fmt, ...); 239 sds sdstrim(sds s, const char *cset); 240 void sdsrange(sds s, ssize_t start, ssize_t end); 241 void sdsupdatelen(sds s); 242 void sdsclear(sds s); 243 int sdscmp(const sds s1, const sds s2); 244 sds *sdssplitlen(const char *s, ssize_t len, const char *sep, int seplen, int *count); 245 void sdsfreesplitres(sds *tokens, int count); 246 void sdstolower(sds s); 247 void sdstoupper(sds s); 248 sds sdsfromlonglong(long long value); 249 sds sdscatrepr(sds s, const char *p, size_t len); 250 sds *sdssplitargs(const char *line, int *argc); 251 sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen); 252 sds sdsjoin(char **argv, int argc, char *sep); 253 sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen); 254 255 /* Low level functions exposed to the user API */ 256 sds sdsMakeRoomFor(sds s, size_t addlen); 257 void sdsIncrLen(sds s, ssize_t incr); 258 sds sdsRemoveFreeSpace(sds s); 259 size_t sdsAllocSize(sds s); 260 void *sdsAllocPtr(sds s); 261 262 /* Export the allocator used by SDS to the program using SDS. 263 * Sometimes the program SDS is linked to, may use a different set of 264 * allocators, but may want to allocate or free things that SDS will 265 * respectively free or allocate. */ 266 void *sds_malloc(size_t size); 267 void *sds_realloc(void *ptr, size_t size); 268 void sds_free(void *ptr); 269 270 #ifdef REDIS_TEST 271 int sdsTest(int argc, char *argv[]); 272 #endif 273 274 #endifView Code
無邊落木蕭蕭下 不盡長江滾滾來
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/541551.html
標籤:其他
上一篇:Django模板控制結構(for/forloop/if)
下一篇:Java String類
