介绍两种生成随机短信验证码的方式,使用运算取代字符串运算的方式,提升十倍生成验证码速度。
方式一(推荐)
生成N位数验证码,纯数字操作,速度快,因为将堆里的运算移动到栈中。
String code = String.valueOf((int)( (Math.random() * 9 + 1) * Math.pow(10, N-1)) )
方式二
生成N位数的验证码,速度慢,需要使用堆内存。
Sring code = (Math.random() + "").substring(2, N+2)
举例
例子:两种方式生成6位验证码一百万次速度对比
//执行一百万次
int sum = 1000000;
long start1 = System.currentTimeMillis();
for (int i=0;i<sum;i++){
//生成验证码 方式一
String code = String.valueOf((int)( (Math.random() * 9 + 1) * Math.pow(10, 5)) );
}
long end1 = System.currentTimeMillis();
System.out.println("方式一耗时:"+(end1-start1));
//===========
long start = System.currentTimeMillis();
for (int i=0;i<sum ;i++) {
//生成验证码 方式二
String code = (Math.random() + "").substring(2, 8);
}
long end = System.currentTimeMillis();
System.out.println("方式二耗时:"+(end-start));
运行结果
方式一耗时:460
方式二耗时:54