Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

random - 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();
     }
}

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...