Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get around for loop bottleneck for constant time operations?
    text
    copied!<p>Working on a rules agnostic poker simulator for fun. Testing bottlenecks in enumeration, and for hands that would always get pulled from the "unique" array, I found an interesting bottleneck. I measured the average computation time of running each of the variations below 1,000,000,000 times and then took the best of 100 repetitions of that to allow JIT and Hotspot to work their magic. What I found was there's a difference in computation time (6ns vs 27ns) between</p> <pre><code>public int getRank7(int ... cards) { int q = (cards[0] &gt;&gt; 16) | (cards[1] &gt;&gt; 16) | (cards[2] &gt;&gt; 16) | (cards[3] &gt;&gt; 16) | (cards[4] &gt;&gt; 16) | (cards[5] &gt;&gt; 16) | (cards[6] &gt;&gt; 16); int product = ((cards[0] &amp; 0xFF) * (cards[1] &amp; 0xFF) * (cards[2] &amp; 0xFF) * (cards[3] &amp; 0xFF) * (cards[4] &amp; 0xFF) * (cards[5] &amp; 0xFF) * (cards[6] &amp; 0xFF)); if(flushes[q] &gt; 0) return flushes[q]; if(unique[q] &gt; 0) return unique[q]; int x = Arrays.binarySearch(products, product); return rankings[x]; } </code></pre> <p>and </p> <pre><code>public int getRank(int ... cards) { int q = 0; long product = 1; for(int c : cards) { q |= (c &gt;&gt; 16); product *= (c &amp; 0xFF); } if(flushes[q] &gt; 0) return flushes[q]; if(unique[q] &gt; 0) return unique[q]; int x = Arrays.binarySearch(products, product); return rankings[x]; } </code></pre> <p>The issue is definitely the for loop, not the addition of handling multiplication at the top of the function. I'm a little baffled by this since I'm running the same number of operations in each scenario... I realized I'd always have 6 or more cards in this function so I brought things closer together by changing it to </p> <pre><code>public int getRank(int c0, int c1, int c2, int c3, int c4, int c5, int ... cards) </code></pre> <p>But I'm going to have the same bottleneck as the number of cards goes up. Is there any way to get around this fact, and if not, could somebody explain to me why a for loop for the same number of operations is so much slower?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload