分析
實際開發中,生成隨機數的場景有很多,比如短信驗證碼、訂單編碼、賬號...
選擇什么方式很重要,下面我們通過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))),效率最高,推薦