zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java HashMap和使用redis读取100000条key-value数据时间性能差异对比

JAVARedis性能数据 时间 读取 对比 Key
2023-09-27 14:21:31 时间
使用java HashMap和使用redisTemplate操作redis的时间性能差异对比

                HashMap完胜,100000条key-value数据。
                使用redisTemplate读取用时5775毫秒,
                HashMap用时6毫秒,
    新建一个springboot工程,导入redis依赖
    打开开发工具创建测试类
    测试取出100000条数据
    测试hashmap
    时间上,hashmap完胜!

先说结论
HashMap完胜,100000条key-value数据。
使用redisTemplate读取用时5775毫秒,
HashMap用时6毫秒,

时间速度约1000倍,
测试代码如下:
新建一个springboot工程,导入redis依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

打开开发工具创建测试类
运行测试,将100000条数据插入redis中

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;

@SpringBootTest
class Demo1ApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        for (int i = 0; i < 100000; i++) {
            redisTemplate.opsForValue().set("key" +i, "你好");
        }
    }
}

 测试取出100000条数据

@Test
    void test2() {
        long l = System.currentTimeMillis();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 100000; i++) {
            String o = (String)redisTemplate.opsForValue().get("key" + i);

            stringBuffer.append(o);
        }

        System.out.println(System.currentTimeMillis() - l);
        System.out.println(stringBuffer.length());

    }
查看结果,redis用时6s左右

 

 

测试hashmap
@Test
    void contextLoads2() {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        for (int i = 0; i < 100000; i++) {
            stringStringHashMap.put("key" +i, "你好");
            //redisTemplate.opsForValue().set("key" +i, "你好");
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long l = System.currentTimeMillis();

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 100000; i++) {
            String o = stringStringHashMap.get("key" + i);

            stringBuffer.append(o);
        }
        System.out.println(System.currentTimeMillis() - l);
        System.out.println(stringBuffer.length());
    }

结果,hashmap用时6毫秒

时间上,hashmap完胜!

集群中用Redis而不用 map/guava(本机快过redis) 做缓存为什么?