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))),效率最高,推薦


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM