Redis的key长度对性能影响分析

Redis的key最大可以多长,太长了对性能会有影响吗?其实这些官方已经给出了解释。

官方解释

Redis keys are binary safe, this means that you can use any binary sequence as a key, from a string like “foo” to the content of a JPEG file. The empty string is also a valid key.

A few other rules about keys:

Very long keys are not a good idea. For instance a key of 1024 bytes is a bad idea not only memory-wise, but also because the lookup of the key in the dataset may require several costly key-comparisons. Even when the task at hand is to match the existence of a large value, hashing it (for example with SHA1) is a better idea, especially from the perspective of memory and bandwidth.

Very short keys are often not a good idea. There is little point in writing “u1000flw” as a key if you can instead write “user:1000:followers”. The latter is more readable and the added space is minor compared to the space used by the key object itself and the value object. While short keys will obviously consume a bit less memory, your job is to find the right balance.

Try to stick with a schema. For instance “object-type:id” is a good idea, as in “user:1000”. Dots or dashes are often used for multi-word fields, as in comment:1234:reply.to or comment:1234:reply-to.

The maximum allowed key size is 512 MB.

正常情况下我们都是用一个字符串作为Redis的key,其实Redis允许使用任何二进制序列作为key,比如像一个JPEG文件的内容。甚至空字符串也是可以的。

关于key使用的一些常识

1.不推荐使用非常长的key。太长的key会造成内存和带宽的浪费。
2.太短的key通常也不推荐使用。比如像这个d1000p,根本看不懂啥意思,可以用device:1000:private代替,可读性更好。
3.最大的key允许512MB

测试Key长度对Redis性能影响

环境

Redis和测试程序都是运行在本地,不看单次的性能,只看不同的长度堆读写性能的影响。

测试方法

使用长度分别为10, 100, 500, 1000, 2500, 5000, 7500, 10,000, and 20,000的key,value长度1000,读写1000次。

从结果来看随着长度的增加,读写的耗时都随之增加。

长度为10:写平均耗时0.053ms,读0.040ms
长度为20000:写平均耗时0.352ms,读0.084ms

测试代码

+2

《Redis的key长度对性能影响分析》有一个想法

发表评论

邮箱地址不会被公开。