Key长度对Redis性能影响

最近Redis的使用中用的到key可能比较长,但是Redis的官方文档没提到key长度对性能的影响,故简单做了个测试。

环境

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

测试方法

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

结果

写

读

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

测试代码

源码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 * 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();
    }
}

Comments

comments powered by Disqus