Course contentsShow
← Java
Lesson 1469 of 2,87032. Streams API: Intermediate OperationsFree lesson

Performance Implications of skip

Explore how skip must consume and discard n elements, understanding its O(n) cost and impact on large offsets.

Performance Implications of skip

What you'll learn: You'll understand why skip() isn't free and how it can create performance bottlenecks when skipping large numbers of elements.

The Hidden Cost of Skipping

Unlike operations that truly short-circuit, skip(n) must consume and discard the first n elements from the stream before passing subsequent elements downstream. This makes skip() an O(n) operation — the cost grows linearly with the number of elements skipped.

Think of it like fast-forwarding through a cassette tape: even though you're not listening, the tape player must physically advance through all that content. You can't magically jump to minute 45 without the mechanism moving through the preceding 44 minutes.

Why This Matters

When you write stream.skip(1000000), the stream pipeline must:

  1. Pull 1,000,000 elements from the source
  2. Evaluate any intermediate operations before skip() on each element
  3. Discard all of them
  4. Only then start producing results

This becomes expensive when:

  • Large offsets: skip(1000000) touches a million elements
  • Costly upstream operations: If map() or filter() precedes skip(), those transformations run on discarded elements too
  • Repeated pagination: Multiple queries with increasing offsets waste work

Practical Impact

// Every page fetch processes ALL previous elements
list.stream()
    .skip(pageNumber * pageSize)  // Page 100 skips 10,000 elements!
    .limit(pageSize)
    .collect(toList());

For deep pagination, consider alternatives like subList on random-access collections or streaming from a different starting point if your data source supports it.

Key Takeaway: skip(n) has O(n) cost because it must consume and discard n elements; avoid large skip offsets when performance matters, especially in repeated pagination scenarios.