You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redis对象编码机制及内存占用差异原因咨询

Why Redis Uses Different Memory for Variations of "1"

Great question! Let’s break down exactly why you’re seeing those memory usage differences in Redis when storing variations of the value "1"—it all comes down to how Redis optimizes storage for different data types under the hood.

1. set a 1 and set a "1" both use 49 bytes

Redis is built to optimize wherever possible. When you run either of these commands:

  • Redis parses the input and recognizes it’s a valid integer that fits in a long long range.
  • Instead of wasting space storing it as a raw string, it uses the int encoding for the string object. This is super compact: the integer value is stored directly in the object’s pointer field, no extra string buffer needed.

The 49 bytes you see covers:

  • The overhead of storing the key "a" (as a small string)
  • The tiny int-encoded value object for 1

Since both commands end up with the same underlying integer storage, their memory usage is identical.

2. set a \x01 (MessagePack-encoded 1) uses 55 bytes

Here, you’re writing a raw binary byte (0x01) to Redis. This is different from the previous cases:

  • Redis can’t interpret this binary value as a string-formatted integer—it’s just a single byte of raw data, not the character "1".
  • So Redis has to store this as a full string object (using embstr encoding for short strings). This requires a proper SDS (Simple Dynamic String) structure, which includes:
    • A small header tracking length, allocated space, and flags (3 bytes for tiny strings)
    • The actual 1-byte binary data
    • A null terminator (1 byte for string safety)
  • Plus the standard overhead of the Redis object wrapper.

All that extra structure adds up compared to the compact int encoding, which is why you see a 6-byte jump in memory usage here.

3. set a '\x01' (quoted MessagePack value)

One quick note on this case: When you wrap \x01 in single quotes in the Redis CLI, the CLI doesn’t parse the escape sequence—it stores the literal string \x01 (four characters: \, x, 0, 1). This would use even more memory than the binary 0x01 case, since it’s storing a 4-character string instead of a single byte.

Key Takeaway

Redis’s memory usage for string values depends entirely on whether it can optimize the value into a numeric encoding. Raw binary data or non-integer strings trigger the more heavyweight SDS storage, while integer-compatible strings get the nice compact int encoding that saves space.

内容的提问来源于stack exchange,提问作者Avba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:44:14