Distribution of Random Numbers

前端 未结 5 875
孤独总比滥情好
孤独总比滥情好 2021-02-04 17:22

I have two options of code:

Option 1

int myFunc() {
  return new Random().nextInt();
}

Or:

Option 2

5条回答
  •  猫巷女王i
    2021-02-04 17:30

    Java initializes the random seed with System.nanoTime() and a sequential counter. This gives somewhat a guarantee that the seed will be different for each invocation, although I would refrain from calling it cryptographically secure.

    From the performance point of view - do you really expect locking on internal state of Random in option 1 to have a larger performance hit then all of the following:

    • accessing and incrementing volatile long
    • getting the current system time (which is quite expensive)
    • dynamic allocation
    • another object for garbage collection

    My suggestion will be to do benchmarks of your real application to find out, but I expect option 1 to be the slowest of all three.

提交回复
热议问题