Sub topic 8
When an isolate is worth it
This chapter assumes basic Dart syntax, async and await, Future, and basic streams. For Flutter examples, also assume that you know why the UI isolate must stay responsive.
An isolate is worth using when a computation takes long enough to block the current isolate and the work can be separated from UI or request-handling code. Creating an isolate, starting its execution, and moving data between isolates all have costs. Moving a small, quick operation to another isolate can make the program slower.
Measure the work before moving it
Dart runs synchronous code without interruption. A loop, parser, image transformation, or compression task keeps running until it returns. While it runs, the current isolate cannot process other events.
In Flutter, this can delay frame work. If the UI isolate misses its frame deadline, the screen appears to stutter. In a server, the same problem delays timers, socket events, and other requests handled by that isolate.
First measure the synchronous operation with realistic input. Consider an isolate when:
- The operation is CPU-bound rather than waiting for a file, network, or database.
- The operation can run independently of the current isolate.
- The operation takes long enough to cause visible jank or delayed events.
- The input and output are reasonably cheap to send.
- The operation happens often enough to justify a worker, or takes long enough to justify one-off startup.
This example compares direct execution with Isolate.run:
import 'dart:isolate';
int fibonacci(int n) {
if (n < 2) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
Future<void> main() async {
final directStart = Stopwatch()..start();
final directResult = fibonacci(35);
directStart.stop();
final isolateStart = Stopwatch()..start();
final isolateResult = await Isolate.run(() => fibonacci(35));
isolateStart.stop();
print('Direct: $directResult in ${directStart.elapsedMilliseconds} ms');
print('Isolate: $isolateResult in ${isolateStart.elapsedMilliseconds} ms');
}The isolate version usually takes longer for a small job because it includes startup and message-transfer overhead. Its value appears when the direct version blocks work that must remain responsive.
Choose one-off work or a worker
Use Isolate.run for an independent, one-off computation. It starts a short-lived isolate, runs the callback, and returns the result through a Future. This is a good fit for parsing a large response, transforming a document, or calculating a report once.
Use a long-lived worker isolate when several jobs will arrive over time. Startup happens once, and a SendPort can carry many requests. The worker also gives you a place to serialize jobs or control concurrency.
| Situation | Suitable choice | Reason |
|---|---|---|
| Small calculation that finishes quickly | Current isolate | Isolate overhead costs more than the work |
| Large JSON parse performed once | `Isolate.run` | The UI or event loop stays free |
| Many similar CPU-heavy jobs | Long-lived worker | Reuse the isolate and its communication channel |
| Network request or database wait | Async API | Waiting does not usually require another isolate |
| Work that needs unsupported plugins | Current isolate or supported API | Background plugin access may fail |
compute in Flutter is another convenient option for one-off work. It accepts a top-level or static function and one argument. On native platforms, it runs that function in another isolate. Its web behavior differs because Dart web does not provide native isolates in the same way.
Account for data and platform limits
Isolates do not share mutable memory. Values passed in messages are copied or transferred according to Dart's isolate rules. Large object graphs can therefore cancel the performance benefit. Keep messages small, and do parsing or transformation inside the worker when possible.
For large byte buffers, TransferableTypedData can transfer ownership more efficiently than copying every byte. After materializing the data in the receiving isolate, the original transferable must not be reused.
A background isolate also cannot automatically use every Flutter plugin. Platform-channel support depends on the plugin and the way the isolate is initialized. A computation that only uses Dart libraries is easier to move safely.
A practical decision rule
Ask these questions in order:
- Is the work CPU-bound and synchronous?
- Does it block a UI frame or delay important events?
- Can its inputs and outputs cross an isolate boundary?
- Is it a one-off task or a repeated stream of tasks?
- Does the target platform and every required library support the operation?
If the first two answers are no, stay in the current isolate. If they are yes, use Isolate.run for one task or a long-lived worker for repeated tasks. Measure again after the change. The goal is lower blocking time, not simply more isolates.
Exercise
A Flutter screen parses a small JSON response in less than one millisecond, but a database call waits for 200 milliseconds. Should both operations use an isolate?
Show answer
No. Keep the small parse on the current isolate and use the database's asynchronous API for the wait. An isolate is more appropriate for CPU-heavy parsing that blocks frames.