我最近读到,您不想在不必要时创建新实例。我不确定我是否明白它在说什么。问题是 LogCat 中重复了这一点:
08-09 17:12:11.300: D/dalvikvm(19620): GC_FOR_ALLOC freed 2281K, 23% free 9365K/12048K, paused 12ms, total 12ms
那么是不是有这个方法比较好:
public int rand(int i) {
int rand = new Random().nextInt(i);
return rand;
}
比使用此方法:
public int rand(int i) {
return new Random().nextInt(i);
}
如果你经常调用 rand() 吗?为什么或者为什么不?感谢您帮助新手!
最佳答案
这样做:
class ... {
private final Random dice = new Random();
public int rand(int i) {
return dice.nextInt(i);
}
}
这样,您只需调用 new Random()
一次,而不是每次生成数字时都调用。
关于java - 随机方法的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18155888/