分析
实际开发中,生成随机数的场景有很多,比如短信验证码、订单编码、账号…
选择什么方式很重要,下面我们通过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),执行时间:500code += random.nextInt(10),执行时间:233String.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))),效率最高,推荐