栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java生成6位随机数方法分析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java生成6位随机数方法分析

分析 

实际开发中,生成随机数的场景有很多,比如短信验证码、订单编码、账号...

选择什么方式很重要,下面我们通过4种生成方式来分析利弊

    public static void main(String[] args) {
        int count = 1000000;
        long start = 0L;
        long end = 0L;

        start = System.currentTimeMillis();
        Random random1 = new Random();
        for (int i = 0; i < count; i++) {
            String.valueOf(random1.nextInt(1000000));
        }
        end = System.currentTimeMillis();
        System.out.println("random.nextInt(num),执行时间:" + (end - start));

        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            (Math.random() + "").substring(2, 8);
        }
        end = System.currentTimeMillis();
        System.out.println("(Math.random() + "").substring(2, 8),执行时间:" + (end - start));

        start = System.currentTimeMillis();
        Random random2 = new Random();
        String code = "";
        for (int i = 0; i < count; i++) {
            for (int j = 0; j < 6; j++) {
                code += random2.nextInt(10);
            }
            code = "";
        }
        end = System.currentTimeMillis();
        System.out.println("code += random.nextInt(10),执行时间:" + (end - start));

        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
        }
        end = System.currentTimeMillis();
        System.out.println("String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10,5))),执行时间:" + (end - start));
    }
执行情况 
random.nextInt(num),执行时间:50
(Math.random() + "").substring(2, 8),执行时间:500
code += random.nextInt(10),执行时间:233
String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10,5))),执行时间:46
结果

random.nextInt(num),生成的值是介于[0,num)的区间,不符合生成固定位数的

(Math.random() + "").substring(2, 8),通过字符串截取,效率最低

code += random.nextInt(10),通过字符串拼接,效率低

String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10,5))),效率最高,推荐

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/758967.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号