English | 中文版
[TOC]
struct sdshdr { /* Redis self-implemented string */
unsigned int len; /* number of used bytes */
unsigned int free; /* number of free bytes */
char buf[]; /* byte array holding the string */
};| Function | Description | Time Complexity |
|---|---|---|
sdsnew |
Create an SDS containing the given C string |
|
sdsempty |
Create an empty SDS | |
sdsfree |
Free the given SDS |
|
sdslen |
Return number of used bytes in SDS |
len field) |
sdsavail |
Return number of free bytes in SDS |
free field) |
sdsdup |
Create a copy of the given SDS |
|
sdsclear |
Clear SDS contents |
|
sdscat |
Concatenate a C string to the end of an SDS |
|
sdscatsds |
Concatenate one SDS to another |
|
sdscpy |
Copy a C string into an SDS (overwrite existing content) |
|
sdsgrowzero |
Expand SDS to the given length and zero the new bytes |
|
sdsrange |
Keep the specified range of the SDS, overwrite/clear others |
|
sdstrim |
Remove from SDS all characters appearing in the given C string |
|
sdscmp |
Compare two SDS strings for equality |
|
When an SDS operation needs to grow the buffer, Redis allocates not only the required bytes but also additional free bytes according to a growth policy:
-
If the SDS length (
len) is less than 1MB, Redis allocates an extra amount equal tolen(double the current size).Example: if
len = 13, the allocated buffer becomes13 + 13 + 1 = 27bytes (the extra+1is for the terminating NUL). -
If the SDS length is >= 1MB, Redis allocates an extra 1MB of free space.
Example: if
len = 30MB, Redis adds1MBfree space and the total buffer is30MB + 1MB + 1 byte.
When an SDS operation shortens the stored string, Redis does not immediately shrink the allocation. Instead it updates the free field to record unused bytes and postpones actual memory reallocation until needed.
| C string | SDS |
|---|---|
| Getting length costs |
Getting length costs |
| Unsafe APIs (risk of buffer overflow) | Safe APIs (no buffer overflow) |
| Reallocating N times for N length changes | At most N reallocations for N changes |
| Stores only text | Stores text or binary data |
Compatible with all <string.h> ops |
Compatible only with a subset of them |
[1] Huang Jianhong. Redis Design and Implementation