Say I have two classes like this:
class A{
private static Random random = new Random();
public A(){
// Do something.
}
public Integer methodGetsCalledQuiteOften(){
return random.nextInt();
}
}
class B{
private Random random;
public A(){
random = new Random();
// Do something.
}
public Integer methodGetsCalledQuiteOften(){
return random.nextInt();
}
}
In a scenario where both of them get instantiated multiple times and both of these classes' instances' method methodGetsCalledQuiteOften
gets called a lot, is there any real advantage/disadvantage (time, memory) in using a static variable that holds Random()
in class A as opposed to creating a new Random()
object in every single instance, like in class B?
The application is multithreaded and higher level of randomness is so I think I am going with static SecureRandom
. If that will be a real speed factor after profiling I might choose something else.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…