audun commented on issue #673: Replace instances of Math.random with 
Random.nextDouble
URL: https://github.com/apache/lucene-solr/pull/673#issuecomment-492543727
 
 
   I ran some benchmarks. 
   
   ```
       @Benchmark
       public void mathRandom(Blackhole bh) {
           for (int i = 0; i < N; i++) {
               double d = Math.random();
               bh.consume(d);
           }
       }
   
       @Benchmark
       public void newRandom(Blackhole bh) {
           for (int i = 0; i < N; i++) {
               Random rand = new Random();
               double d = rand.nextDouble();
               bh.consume(d);
           }
       }
   
       @Benchmark
       public void reuseNewRandom(Blackhole bh) {
           Random rand = new Random();
           for (int i = 0; i < N; i++) {
               double d = rand.nextDouble();
               bh.consume(d);
           }
       }
   ```
   
   
   In a single-threaded benchmark the proposed way is about three times slower 
than Math.random:
   
   ```
   Benchmark                          (N)  Mode  Cnt    Score    Error  Units
   BenchmarkLoop.mathRandom      10000000  avgt   10  228.864 ±  2.904  ms/op
   BenchmarkLoop.newRandom       10000000  avgt   10  749.884 ±  8.158  ms/op
   BenchmarkLoop.reuseNewRandom  10000000  avgt   10  236.233 ± 11.580  ms/op
   ```
   
   Since Math.random is synchronized it has significant problems in a 
multi-threaded benchmark:
   
   ```
   Benchmark                          (N)  Mode  Cnt      Score     Error  Units
   BenchmarkLoop.mathRandom      10000000  avgt   10  12878.414 ± 628.863  ms/op
   BenchmarkLoop.newRandom       10000000  avgt   10   5583.754 ± 221.973  ms/op
   BenchmarkLoop.reuseNewRandom  10000000  avgt   10    270.047 ±  14.086  ms/op
   ```
   
   Note that  this benchmark is quite unrealistic for most workloads, since 
it's doing nothing apart from generating random numbers and will hit the 
synchronization lock every single time.
   
   The consistent winner here seems to be a thread-local `Random` object and 
repeatedly getting a random number from that.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to