This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging

String objects

1, string object introduction and features 2, encoding conversion 3, string part command implementation

1. Introduction and features of string objects

String objects can be int, raw, or embstr.

  • A string object holds an integer value that can be represented as a long, so the string object stores the integer value in the PTR property of the string object structure (converting void* to long) and sets the encoding of the string object to int.
  • If the string object holds a string value greater than 39 bytes in length, the string object uses a simple dynamic string (SDS) to hold the string value and sets the object’s encoding to RAW.
  • If a string object holds a string value that is less than or equal to 39 bytes in length, the string object will use the embstr encoding to hold the string value.

Using embstr-encoded string objects to hold short string values has the following benefits: 1. Embstr encoding reduces the memory allocation required to create string objects from two raw encoding times to one. To free an embstr-encoded string object, you only need to call the memory free function once. To free an EMbstr-encoded string object, you need to call the memory free function twice. 3. Since all data of an embSTR-encoded string object is stored in one contiguative chunk of memory, embstr-encoded string objects can take advantage of caching better than raw string objects.

Raw encodes a string object

Embstr-encoded string object

Finally, note that floating-point numbers that can be represented as long double are also stored as string values in Redis.

2, coding conversion

Int – encoded string objects and embstr-encoded string objects are converted to raw – encoded string objects if conditions are met. 1. For an int encoded string object, the encoding of the string object changes from int to RAW if we execute some command to the object that holds a string value instead of an integer value. Redis does not write any modification programs for embstr-encoded string objects (only int and RAW string objects have these programs), so embstr-encoded string objects are actually read-only. When we modify embstr-encoded string objects, Redis does not write any modification programs for embstr-encoded string objects. The program will be transformed.

The following example shows an embstr-encoded string object whose encoding changes from embstr to RAW after executing the APPEND command:

redis> SET msg "hello world"
OK
redis> OBJECT ENCODING msg
"embstr"
reids> APPEND msg " again!"
(integer) 18
redis> OBJECT ENCODING msg
"raw"
Copy the code