Sub topic 8
When an isolate is worth it
An isolate keeps heavy work off the thread that runs your UI, but it has costs of its own. This chapter gives you a way to decide when the trade is worth making. It assumes you know async/await, you have used Isolate.run, and you know that isolates have separate heaps and communicate by copying messages. For Flutter, it assumes you know that the UI isolate must build a frame within a fixed time budget.
What an isolate costs
Moving work to another isolate is never free. You pay in four ways:
- Startup.
Isolate.runcreates a new isolate for each call. This is cheap compared with an operating system process, but it is not zero. For a task that takes microseconds, the setup costs more than the task. - Copying inputs. Everything the closure captures is copied into the new isolate's heap. A large
ListorMapis copied element by element. AStringor a list of plain objects can cost real time before your code even starts. - Returning results.
Isolate.runsends its result back usingIsolate.exit. That can hand over the result without a full copy, but it does not work for every value. Treat the return trip as a cost you have to measure. - Memory. Each isolate has its own heap. If you copy a 50 MB payload into a worker, you briefly hold two copies.
An isolate also adds complexity. Errors cross a boundary, closures can capture too much, and plugin calls need extra setup. Add an isolate when it removes a measured problem. Don't add one as a precaution.
What an isolate buys
Dart runs the code of one isolate on a single event loop. While a synchronous function runs, no other event in that isolate is handled. That includes taps, timers, animation ticks and frame builds.
In Flutter, a frame at 60 Hz has about 16 ms. At 120 Hz it has about 8 ms. Your build, layout and paint work shares that budget. If one synchronous call takes 40 ms, you skip at least two frames and the user sees a stutter.
The benefit of an isolate is therefore responsiveness, not always speed. The total work done is the same, and it can even take longer in wall-clock time because of the copying. What changes is that the UI isolate stays free to handle events. Parallel speed-up is a secondary benefit, and it only happens when the device has idle cores.
Measure before you decide
Do not guess whether a function is slow. Time it, and in Flutter do it in profile mode. Debug builds are much slower than release builds and will overstate the problem. The Performance view in Flutter DevTools shows frames that exceed the budget and what ran during them.
You can also measure the thing you care about, which is how long the event loop was unavailable. This pure Dart program does that. It runs a timer every 5 ms and records the longest gap between ticks, once with the work on the main isolate and once with the work in Isolate.run.
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
String buildPayload() => jsonEncode([
for (var i = 0; i < 300000; i++) {'id': i, 'name': 'item $i'},
]);
Future<int> maxGapMs(Future<void> Function() work) async {
final watch = Stopwatch()..start();
var last = 0;
var maxGap = 0;
final timer = Timer.periodic(const Duration(milliseconds: 5), (_) {
final now = watch.elapsedMilliseconds;
if (now - last > maxGap) maxGap = now - last;
last = now;
});
await work();
// Let the timer fire once more so a blocked loop shows up as a late tick.
await Future<void>.delayed(const Duration(milliseconds: 20));
timer.cancel();
return maxGap;
}
Future<void> main() async {
final raw = buildPayload();
final blocked = await maxGapMs(() async {
jsonDecode(raw);
});
final offloaded = await maxGapMs(() => Isolate.run(() => jsonDecode(raw)));
print('Longest gap, main isolate: $blocked ms');
print('Longest gap, Isolate.run: $offloaded ms');
}The first number is roughly the time jsonDecode took, because nothing else could run. The second should stay near the 5 ms timer interval. Absolute values depend on your machine, but the pattern holds.
Work that does not need an isolate
The most common mistake is to offload work that is not CPU-bound. A Future does not make code parallel. It lets the event loop do other things while it waits. Network requests, file reads and database queries through a plugin already wait outside the isolate's thread. The runtime or the platform does the waiting, and your isolate only handles the result.
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
List<Object?> _decode(String raw) => jsonDecode(raw) as List<Object?>;
Future<List<Object?>> loadItems(String path) async {
// I/O: the event loop stays free while the read is in progress.
final text = await File(path).readAsString();
// CPU: decoding a large document is synchronous work, so offload it.
return Isolate.run(() => _decode(text));
}The await on the file read needs no isolate. The decode does, but only if the document is large enough to matter.
A decision flow
Typical cases
| Task | Isolate? | Reason |
|---|---|---|
| Decoding a multi-megabyte JSON response | Yes | CPU-bound and long enough to drop frames |
| Awaiting an HTTP response | No | Waiting, not computing |
| Resizing or filtering a large image in Dart code | Yes | CPU-bound, large but easy to send as bytes |
| Parsing a 2 KB JSON string | No | Setup and copying cost more than the parse |
| Computing a hash of a large file in Dart | Yes | CPU-bound, run in parallel with the UI |
| Updating a widget's state | No | UI objects belong to the main isolate |
| Hundreds of small jobs per second | Worker | One long-lived isolate avoids repeated startup |
Edge cases and thresholds
Size can decide it. The same function can be cheap for small input and expensive for large input. A threshold lets you skip the isolate when it would not help. Pick the cutoff by measuring on a low-end device, not on your development machine.
import 'dart:convert';
import 'dart:isolate';
List<Object?> _decode(String raw) => jsonDecode(raw) as List<Object?>;
Future<List<Object?>> decodeList(String raw) {
const cutoff = 100 * 1024; // characters; tune this by measuring
if (raw.length < cutoff) {
return Future.value(_decode(raw));
}
return Isolate.run(() => _decode(raw));
}The closure captures only raw, and _decode is a top-level function, so nothing else travels to the new isolate.
Many small jobs. Calling Isolate.run in a loop pays the startup cost every time. If you have a steady stream of requests, such as filtering a list on every keystroke, use one long-lived worker instead. Batching several items into one call also helps.
Large inputs that you build up. If your input is a huge object graph, the copy can take as long as the work. Pass compact data such as a Uint8List or a String, and consider TransferableTypedData for byte buffers. If the copy dominates, an isolate may not be worth it.
Parallel speed-up is limited by cores. Spawning eight isolates on a device with two available cores will not make the work four times faster. For responsiveness one background isolate is usually enough.
Work that touches UI or plugins. Widgets, BuildContext and other UI objects cannot leave the main isolate. Plugin calls from a background isolate need extra setup and plugin support. If the heavy part of the task is a plugin call, check that first.
The web. Dart compiled to JavaScript does not have isolates in the same sense, and Isolate.run is not available there. Flutter's compute runs the work on the calling thread on the web, so it does not prevent jank. For the web, the options are splitting the work into smaller chunks that yield to the event loop, or using a web worker. A later chapter covers platform limits.
A practical checklist
- Reproduce the slowness in profile mode on a real, ideally low-end, device.
- Confirm in DevTools that the time is spent in synchronous Dart code, not in waiting.
- Check that the inputs and results can be sent, and keep closures small.
- Start with
Isolate.runorcompute. Move to a worker only if you see repeated startup cost. - Measure again, and keep the isolate only if the dropped frames or event delays are gone.
Exercise
A screen calls await http.get(url) and then decodes a 20 KB JSON response. Users report stutter. A profile shows no long frames during the request. Should you wrap the request in Isolate.run? What would you check first?
Show answer
No. The request is I/O, so the await already leaves the event loop free. A 20 KB decode is also small and probably takes well under a frame, so an isolate would likely cost more than it saves. Check the profile for the real source of the stutter, for example expensive builds, large images, or layout work, and only offload the decode if it shows up as a long synchronous block.
Exercise
Your app filters a list of 50,000 items each time the user types a letter. Each filter takes about 30 ms. Which approach fits best: Isolate.run on every keystroke, or a long-lived worker? Give two reasons.
Show answer
A long-lived worker fits better. First, it avoids paying isolate startup on every keystroke. Second, you can send the list to the worker once and then send only the short query string, which avoids copying 50,000 items repeatedly. You should also ignore or cancel stale results so a slow earlier query does not overwrite a newer one.