简体   繁体   中英

Should I create my object “Random r” before or in my loop

What I want to know is:
I have a Random object r which is currently being created in the while loop.
And I have 3 places where I could create it.

  1. Right when the main() starts
  2. In the while() loop
  3. In the for() loop

Question is: What are the differences? has any of those any advantage or disadvantage.
Is there a difference in performance? Is the randomness affected?

What I know is that I cannot use r outside of the loop as it stops existing once the loop terminates. So if I want to use r for any other thing it may be required. (right?)

    import java.util.*;

    class test{
    public static void main(String[] args) {

        int numberOfTrue = 0;
        long loopCounter = 0;
        int howManyInts = 20;

        while(numberOfTrue != howManyInts){
            loopCounter += 1;
            numberOfTrue = 0;

            Random r = new Random();

            for(int a = 0; a < howManyInts; a++){       
                if(r.nextBoolean()){
                    numberOfTrue += 1;
                }else{
                   break; 
                }
            }
        }
        System.out.println("It took " + loopCounter + " loops to get " + howManyInts + " random values which are all even.");
    }
}

The program creates "endless" random numbers and if it created howManyInts of 0 in a row it terminates.

EDIT1: Changed the code a little as @Peter Lawrey suggested and changing if(r.nextInt(2) % 2 == 0) to if(r.nextBoolean()) and also renamed some variables to fit the new code

I love to help you help me and I can cope with strong criticism. Don't hold back.

你肯定应该在循环之外创建它,因为对于每次迭代,它将在内存中无用的对象分配,对于大型数据集,你可能无缘无故地丢失大量内存。

  • First of all it should be created outside both of your loops, otherwise it will always allocate a new memory for it instead you can use the same If you use it outside, yes you will save memory.
  • In terms of performance - it wont b any issue here, now a days we have good cache and RAM so no performance issue
  • No the randomness would not affect your code here, every time you create new object of Random class the constructor would increment the seedUniquifier and add the nano seconds from system value

You can do this with nextInt to get many bits at once.

Random rand = new Random();
int count;
for(count = 0; ; count++)
    if (rand.nextInt(1 << 20) == 0) // 20 bits which are all zero in a row.
        break;
System.out.println("It took "+count+" loops to get 20 even values in a row");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM