Key长度对Redis性能影响
最近Redis的使用中用的到key可能比较长,但是Redis的官方文档没提到key长度对性能的影响,故简单做了个测试。
环境
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
测试代码
/**
* Created by addo on 2017/3/16.
*/
public class RedisTest {
private static String[] keys = new String[1000];
private static String randomString(int length) {
Random random = new Random();
char[] chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
StringBuilder key = new StringBuilder(length);
int i = length;
while (i > 0) {
key.append(chars[random.nextInt(chars.length)]);
i--;
}
return key.toString();
}
private static void write(Jedis jedis, int length) {
long start = System.currentTimeMillis();
String key = null;
String value = null;
for (int i = 0; i < 1000; i++) {
key = randomString(length);
keys[i] = key;
value = randomString(1000);
jedis.set(key, value);
}
System.out.println(String.format("put key length %d with value length 1000 in 1000 tims costs: %d ms", length, System.currentTimeMillis() - start));
}
private static void read(Jedis jedis, int length) {
long start = System.currentTimeMillis();
for (int i = 0; i < keys.length; i++) {
jedis.get(keys[i]);
}
System.out.println(String.format("get key length %d with value length 1000 in 1000 tims costs: %d ms", length, System.currentTimeMillis() - start));
}
public static void main(String[] args) throws InterruptedException {
Jedis jedis = new Jedis("localhost", 6379);
int[] lengths = {10, 100, 500, 1000, 2500, 5000, 7500, 10000, 20000};
for (int i = 0; i < lengths.length; i++) {
write(jedis, lengths[i]);
read(jedis, lengths[i]);
keys = new String[1000];
jedis.flushAll();
}
System.out.println();
}
}