D
PerformanceHard50 XP4 min read

When should you use an Isolate for performance?

TL;DR: Move CPU-intensive work (JSON parsing, image processing, encryption, sorting large lists) to an Isolate using compute() or Isolate.run() to prevent blocking the UI thread (main isolate).

Full Answer

Dart is single-threaded per isolate. Any computation that takes >8ms on the main isolate risks dropping a 60fps frame. Heavy work must be offloaded.

compute() vs Isolate.spawn()

  • compute(fn, data): Spawns a fresh isolate, runs fn(data), returns result, disposes isolate. Simple one-shot tasks
  • Isolate.run(fn): Flutter 3.7+ equivalent of compute, with better error handling
  • Isolate.spawn(): Full control over long-lived isolates with bidirectional ports. For persistent background workers
⚠️

Isolates don't share memory — you can only pass primitive types, simple objects that are serializable. You cannot pass BuildContext, ChangeNotifier, or streams to an Isolate.

Code Examples

dartcompute() for JSON parsing
Output
// Main thread stays free; parsing happens in parallel

Common Mistakes

  • Using compute() for fast operations (<1ms) — spawning an isolate has overhead (~10ms)
  • Trying to pass complex objects with closures to an isolate — they must be serializable

Interview Tip

💡

The rule of thumb: if a computation could take >8ms (one frame at 60Hz), offload it. JSON parsing of API responses >100KB is a classic candidate.

#isolate#compute#background-thread#jank