Description
Dm: Method uses the nextDouble method of Random to generate a random integer; using nextInt is more efficient
使用nextDouble去產生一個random integer,造成效能降低。
Solution
If r is a java.util.Random, you can generate a random number from 0 to n-1 using r.nextInt(n), rather than using (int)(r.nextDouble() * n).
用nextInt(n)取代(int)(r.nextDouble() * n)即可。
Example
Before:
private static void delay(){ int d = (int)(Math.random()*1000); try { Thread.sleep(d); } catch (InterruptedException e) { // log.. } }
After:
private static void delay(){ int d = r.nextInt(1000); try { Thread.sleep(d); } catch (InterruptedException e) { // log.. } }
PS. Math.random()內也是會去產生Random物件去取得亂數值。
留言
張貼留言