Why Random Numbers Drain CPU: Low‑Load Performance Test of Random vs Int vs AtomicInteger
A low‑load performance test compares three ways of selecting an array index—using Math.random(), a sequential int counter, and AtomicInteger—revealing that the random‑number approach consumes significantly more CPU while AtomicInteger spikes memory usage under higher loads.
Background
In a previous article the author compared three methods for picking a random element from an array: using a random number generator, incrementing an int, and incrementing an AtomicInteger. The earlier tests ran at very high QPS and hit CPU limits, so a new, lower‑load test was designed to obtain more realistic performance differences.
Test Design
The test uses a fixed QPS model; each run adds a 10 ms artificial delay to simulate response time. The array‑access step is identical for all three implementations, only the index calculation differs. The core test code is:
import com.funtester.frame.SourceCode
import com.funtester.frame.execute.FunQpsConcurrent
import groovy.util.logging.Log4j2
import java.util.concurrent.atomic.AtomicInteger
@Log4j2
class Ts extends SourceCode {
static void main(String[] args) {
def total = 1000_0000
def index = new AtomicInteger()
int i = 0
def test = {
i++ % total
// index.getAndIncrement() % total
getRandomInt(total)
sleep(0.01)
}
new FunQpsConcurrent(test, "测试随机性能").start()
}
}Results
Data were collected with IntelliJ’s built‑in profiler. The key metrics are TPS (ten‑thousands per second) and CPU usage (%). Summarised findings:
At 1 wan TPS, CPU: random 13 %, int 15 %, atomic 12 %.
At 2 wan TPS, CPU: random 26 %, int 30 %, atomic 24 %.
At 3 wan TPS, CPU: random 38 %, int 46 %, atomic 38 %.
At 4 wan TPS, CPU: random 51 %, int 60 %, atomic 51 %.
At 5 wan TPS, CPU: random 64 %, int 75 %, atomic 64 %.
Random‑number generation consistently incurs the highest CPU cost. Memory usage was not listed for the first two methods, but the atomic implementation showed a noticeable increase, reaching up to ~130 MB heap, whereas random and int stayed around 50 MB.
Additional Observation
An unexpected pattern appeared when the test order changed (e.g., running 10 k TPS before 50 k TPS or vice‑versa). CPU differences seemed linked to the growth of active threads, suggesting that thread‑switching overhead dominates the observed CPU variance. The author plans to add explicit thread‑count comparisons in future tests to further optimise the FunTester framework.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
