Intermediate 25 min read

CPU Time and Heap Size

By the end of this lesson, you'll be able to:

  • Explain what CPU time and heap size measure, distinct from query/DML counts
  • Identify code patterns that risk each limit
  • Recognize these as less common but real limits, worth knowing about

Prerequisites: "Using the Limits Class"

CPU time: how long code actually computes

// A CPU-time risk: heavy computation, no database operations at all
for (Integer i = 0; i < 1000000; i++) {
    String result = someExpensiveStringManipulation(i);
}

The 10-second CPU time limit measures actual computation time — notably, it does not count time spent waiting on a database query or an external callout (a later Integration module). A tight loop doing heavy calculation, with zero SOQL or DML involved, is exactly the kind of code that risks this limit while having nothing to do with bulkification.

Heap size: how much memory is in use at once

// A heap-size risk: holding a huge amount of data in memory simultaneously
List<Account> allAccounts = [SELECT Id, Name, Description FROM Account]; // could be millions of records

The 6 MB heap limit caps how much data can exist in memory at one time during synchronous execution. This is exactly why Module 20's "SOQL For Loops" lesson matters beyond just being a stylistic choice — a SOQL for loop processes records in batches, keeping heap usage low, while assigning a genuinely massive query result straight to a List risks this limit directly.

Less common, but real

Most everyday Apex code — following this module's bulkification patterns — never comes close to either limit; SOQL/DML limits are what beginners hit far more often. CPU time and heap size become genuinely relevant in specific scenarios: complex calculations over large in-memory collections, or code that (against the previous lesson's advice) loads an enormous result set directly into a List. Worth knowing they exist, even if they surface less often in day-to-day work.

Exercise

As a comment, explain why waiting on a SOQL query does not count against the CPU time limit, but a tight computational loop does.

Show hint

Think about what "CPU time" specifically measures.

APEX

CPU Time and Heap Size Quiz

1. Does time spent waiting on a SOQL query count against the CPU time limit?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

CPU time and heap size are governor limits about computation and memory, not database operations — different failure modes from the SOQL/DML limits covered earlier in this module.