在Java中使用静态变量的优点 [英] Advantage of using static variables in Java
问题描述
假设我有两个这样的类:
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();
}
}
在两个实例化多次实例化的情况下并且这两个类的'实例'方法 methodGetsCalledQuiteOften
被大量调用,是否有任何真正的优势/劣势(时间,内存)使用a在A类中保存 Random()
的静态变量,而不是在每个实例中创建一个新的 Random()
对象,就像在B类一样?
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?
该应用程序是多线程的,随机性水平较高,所以我认为我将使用静态 SecureRandom
。如果在分析后这将是一个真正的速度因素,我可能会选择其他东西。
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.
推荐答案
真正的优势/缺点取决于真正的代码。换句话说,它取决于创建 B
的频率与调用该方法的频率等相比。您应该分析您的应用程序并查看它是否有合理的差异。
Real advantage/disadvantages depend on real code. In other words, it depends on how often a B
is created compared to how often the method is called, etc. You should profile your application and see whether it makes a reasonable difference.
A会比B更高效吗?当然。但是,你是否会注意到取决于你的用法。 A会比B使用更少的内存吗?当然,但你是否关心取决于你要保留多少个A / B实例。
Will A be more performant than B? Certainly. But whether you'll ever notice depends on your usage. Will A use less memory than B? Certainly, but whether you care or not depends on how many instances of A/B you're keeping around.
真正唯一的另一个考虑因素是决定论。由于您没有为Random实例指定种子,我认为您不关心是否可以从Random重现数字序列。但是值得注意的是......如果你有一个共享的随机数,那么为某个A实例保证一定数量的确定性数字序列要比在B中每个实例保证一个确定的数字序列要困难得多。
Really the only other consideration is determinism. Since you don't specify the seed for the Random instance, I take it you don't care whether you can reproduce the sequence of numbers from the Random. But it's worth noting...if you have a shared Random, it will be much harder to guarantee a certain deterministic sequence of numbers for some instance of A than it is with one per instance as in B.
这篇关于在Java中使用静态变量的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!