Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

Compare the cost of filling, searching and summing a large int[] with a for loop, Arrays.fill, Arrays.stream(a).sum() and IntStream.parallel(). When does each make sense in a service?

For filling and copying, Arrays.fill and System.arraycopy are as fast as or faster than a hand-written loop, because the JIT compiles them to optimised machine code; System.arraycopy is a true intrinsic. For summing, a plain for loop over int[] is often auto-vectorised by C2, and Arrays.stream(a).sum() is close behind but adds overhead that matters for small arrays. Parallel streams split work across the common ForkJoinPool and only pay off for large, CPU-bound arrays, while hurting latency in a busy service. Arrays.parallelSort and parallelPrefix exist for big data, and we decide all of this with JMH, not System.nanoTime loops.

Why this question is asked

In a service, array work usually hides inside something else: building a response, scoring candidates, aggregating metrics. When it shows up in a profile, the temptation is to reach for a parallel stream or to hand-optimise a loop. Interviewers ask this question to see whether we know what the JIT already does for us, when parallelism helps and when it harms, and how to measure properly. In this answer, we will recap what the JIT does with array code, then look at filling, summing and searching in turn, examine parallel streams in a server, and finish with how to benchmark it without fooling ourselves.

1A Quick Recap: What the JIT Does With Array Loops

HotSpot starts by interpreting our code and then compiles hot methods with C2, its optimising compiler. Two optimisations matter here. An intrinsic is a JDK method that the JIT replaces with hand-tuned machine code instead of compiling its Java body; System.arraycopy is the classic example. Auto-vectorisation is when C2 turns a simple loop into SIMD instructions, which process several ints per instruction, for example 8 ints at once with 256-bit AVX2 registers.

C2 can vectorise a loop when it is simple: a counted loop over an array, no method calls it cannot inline, and no dependency between iterations other than a recognised pattern such as a sum. That is why simple loops over primitive arrays are often faster than they look.

2Filling and Copying

Arrays.fill(a, v) is written in the JDK as a simple loop, which C2 compiles very well, and on common platforms it can replace the loop with an optimised fill routine (check your JDK and platform for the exact behaviour). System.arraycopy is an intrinsic and uses the fastest copy the CPU offers. In both cases the JDK method is at least as fast as our own loop and states the intent more clearly.

Java
int[] a = new int[1_000_000];
Arrays.fill(a, 7); // same speed as a hand loop, or faster
int[] b = new int[a.length];
System.arraycopy(a, 0, b, 0, a.length); // intrinsic: optimised copy routine
// A note: new int[n] is already zeroed, so Arrays.fill(a, 0) on a fresh array is wasted work.

So the rule is simple: use the JDK methods. Hand-written fill or copy loops add no speed and add places for off-by-one errors.

3Summing: Loop Versus Stream

Summing is a reduction, where each iteration depends on the running total. C2 recognises an int sum as a reduction it can vectorise in many cases, keeping several partial sums in a SIMD register and adding them at the end.

Java
static long loopSum(int[] a) {
long s = 0;
for (int i = 0; i < a.length; i++) s += a[i]; // simple counted loop: a good vectorisation candidate
return s;
}
int[] a = new int[10_000_000];
Arrays.fill(a, 1);
System.out.println(loopSum(a)); // 10000000
System.out.println(Arrays.stream(a).sum()); // 10000000 (returns int: can overflow)
System.out.println(Arrays.stream(a).asLongStream().sum()); // 10000000 as a long

Arrays.stream(a).sum() builds a small pipeline object and runs the loop through a Spliterator. For a large array, once the JIT has inlined everything, it is usually close to the plain loop. For small arrays, say 20 elements on a hot path, the fixed setup cost is a noticeable share of the total. Notice also that IntStream.sum() returns an int and overflows silently for large totals, while our loop accumulates in a long.

4Searching

For an unsorted array, a linear scan is the only option, and a simple loop is fine. Arrays.mismatch(a, b), which finds the first index where two arrays differ, uses a vectorised implementation inside the JDK, so for comparing arrays it beats a hand loop. For a sorted array, Arrays.binarySearch finds a value in O(log n): about 24 comparisons for 10 million elements instead of up to 10 million. If a service searches the same large array many times, sorting it once, or building a HashSet or an index, is the real optimisation, far beyond any micro-tuning of the loop.

5Parallel Streams in a Service

IntStream.range(0, n).parallel() or Arrays.stream(a).parallel() splits the array into chunks and processes them on the common ForkJoinPool, a shared pool that by default has one thread fewer than the number of CPU cores. On an idle 16-core machine, summing 100 million ints in parallel can be several times faster than sequentially.

Step throughShould this array operation run in parallel?
  1. Large array, millions of elements?
    YesContinueNoStay sequential
  2. CPU-bound with no blocking or locks?
    YesContinueNoStay sequential
  3. Machine otherwise idle, such as a batch job?
    YesParallel can help: measure itNoStay sequential in request paths

3 steps in order. Play them, or step through them one at a time.

In a request-serving service, all cores are usually already busy with other requests.

But a service is rarely idle. If 200 requests are in progress and each one starts a parallel stream, they all compete for the same few common pool threads. Requests wait for each other, latency becomes unpredictable, and the total throughput often goes down because of the extra coordination. Blocking work, such as calling a database inside a parallel stream, can make the shared pool stall for the whole application, since other libraries use it too. So in request paths we stay sequential, and we use parallel streams in batch jobs or background processing, where one large task can use the whole machine.

For large data, the JDK also has Arrays.parallelSort, which sorts big arrays using the fork/join framework and falls back to a sequential sort below a threshold, and Arrays.parallelPrefix, which computes running totals such as cumulative sums in parallel. The same advice applies: they help on large arrays when cores are free.

6Measuring It Properly With JMH

A loop like long t = System.nanoTime(); loopSum(a); System.out.println(System.nanoTime() - t) measures the wrong thing. The first runs are interpreted, so we time the warm-up. If we do not use the result, the JIT may remove the computation as dead code and we time nothing. JMH handles both: it runs warm-up iterations, consumes results through a Blackhole or the return value, and repeats measurements to report an error margin.

Java
@State(Scope.Thread)
public class SumBench {
@Param({"16", "10000", "10000000"}) int size;
int[] a;
@Setup public void setup() { a = new Random(1).ints(size).toArray(); }
@Benchmark public long loop() { long s = 0; for (int v : a) s += v; return s; }
@Benchmark public long stream() { return Arrays.stream(a).asLongStream().sum(); }
@Benchmark public long parallel() { return Arrays.stream(a).parallel().asLongStream().sum(); }
}
// Run with several sizes: the winner changes with size, which is the point of the exercise.

Running the parallel benchmark on an idle laptop tells us nothing about a loaded server, so for that case we also measure the service under realistic concurrent load and look at the latency percentiles, not only the average.

7Follow-up questions

Is a for-each loop slower than an indexed loop over an array?

No. For arrays, the compiler turns for (int v : a) into an indexed loop, so the JIT sees the same code. Choose whichever reads better.

Can we give a parallel stream its own pool?

A common trick is to run the stream inside a custom ForkJoinPool's submit, which makes it use that pool. It works in current JDKs but relies on implementation behaviour, so check your version, and it still uses CPU that other requests need. A dedicated executor for batch work is usually clearer.

When would you use the Vector API instead?

When C2 does not vectorise a loop we need to be fast, for example with complex conditions inside the loop. In Java 25 the Vector API is still an incubator module, so it needs a command-line flag and its API may change; it suits contained, measured kernels rather than general service code.

8Conclusion

In this answer, we saw that Arrays.fill and System.arraycopy are as fast as or faster than hand loops, because the JIT compiles them to optimised code, with arraycopy as a true intrinsic. A plain for loop sum is often auto-vectorised by C2, Arrays.stream(a).sum() is close for large arrays but adds overhead for small ones and returns an overflow-prone int, and sorting or indexing beats any tuning of linear search. Parallel streams use the shared common ForkJoinPool and only help large CPU-bound work on free cores, so they belong in batch jobs, not request paths, alongside Arrays.parallelSort and parallelPrefix for large data. JMH, run across several sizes, is how we decide.

What to say in the interviewAbout 80 seconds aloud

Open with

For filling and copying I'd always use Arrays.fill and System.arraycopy. arraycopy is a JIT intrinsic, and fill compiles to code that's at least as fast as a hand loop, so writing our own adds risk and no speed.

Then, if they want more

For summing, a simple indexed loop over an int[] is a good candidate for C2's auto-vectorisation, so it's very fast; Arrays.stream(a).sum() gets close on large arrays but has setup overhead that shows on small arrays in hot paths, and it returns an int, so I'd use asLongStream if overflow is possible.

For searching, if I search repeatedly, sorting once and using binarySearch or building a set matters far more than the loop itself. Parallel streams are where I'm careful. They run on the common ForkJoinPool, which has about one thread per core and is shared by the whole JVM.

They can speed up a big CPU-bound computation on an idle machine, but in a service handling hundreds of concurrent requests, the cores are already busy, so parallel streams add contention and make latency worse. I'd keep them, and Arrays.parallelSort or parallelPrefix, for batch jobs on large data.

And I'd decide with JMH across several array sizes, not with System.nanoTime around a loop, because of warm-up and dead code elimination.

About this answer

Last updated
12 November 2026
Versions it names
Java 25
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Compare the cost of filling, searching and summing a large int[] with a for loop...": https://scrivio-interview-library.netlify.app/java/arrays/33960a9a4b/