Math.random()*n か それともRandom.nextInt(n)か
答えから書くと、Random.nextInt(n)を使うべき。
2倍程度高速な上に、ばらつきも良い。
それに、Math.random()*nだと保守性も低いし。
なぜかというと、Math.randomはRandom.nextDoubleを内部で呼び出し、また、nextDoubleはnextIntを二度内部で呼び出しているためである。
一応コード。
package bench; import java.util.Random; public class Main{ Random r; public Main(){ r = new Random(); } public int random(int n){ return (int)Math.random()*(n+1); } public int randInt(int n){ return r.nextInt(n+1); } public int newrandInt(int n){ Random a = new Random(); return a.nextInt(n+1); } public long test1(int x){ long start = System.currentTimeMillis(); for(int i=0;i<x;i++) random(i); long end = System.currentTimeMillis(); System.out.println(x+ " times of Math.random() :" +(end-start) + "ms"); return end-start; } public long test2(int x){ long start = System.currentTimeMillis(); for(int i=0;i<x;i++) randInt(i); long end = System.currentTimeMillis(); System.out.println(x+ " times of r.nextInt() :" +(end-start) + "ms"); return end-start; } public long test3(int x){ long start = System.currentTimeMillis(); for(int i=0;i<x;i++) newrandInt(i); long end = System.currentTimeMillis(); System.out.println(x+ " times of newrandInt() :" +(end-start) + "ms"); return end-start; } public void run(){ int n = 100000000; test1(n); test2(n); test3(n); } public static void main(String[] args){ new Main().run(); } }
実行結果。
100000000 times of Math.random() :6795ms 100000000 times of r.nextInt() :3481ms 100000000 times of newrandInt() :131125ms
だから、コンストラクタとかでRandomをnewしておいて、それを使ってnextIntを呼び出すのが一番よい。
参照: http://stackoverflow.com/questions/738629/math-random-versus-random-nextintint