Chuyển đến nội dung chính

Bài đăng

Hiển thị các bài đăng có nhãn Isolates

Isolate trong Flutter: cái gì thật sự rời khỏi UI thread, cái gì thì không

Hiểu lầm đắt đỏ nhất khi tối ưu hiệu năng Flutter là nghĩ async nghĩa là “chạy ở thread khác”. Không phải. Đánh dấu một hàm là async không thay đổi chút nào chuyện thân hàm chạy ở đâu — mọi câu lệnh vẫn chạy trên isolate đã gọi nó, mà trong app Flutter thì gần như luôn là UI isolate , chính cái isolate đang build widget và chạy animation cho bạn. Thứ await mang lại là một điểm tạm dừng (suspension point). Hàm chạy tới await đầu tiên, trả quyền điều khiển về event loop, rồi tiếp tục khi future được await hoàn tất. Giữa hai điểm tạm dừng, code của bạn chiếm trọn thread và không có gì khác — không cú chạm nào, không frame nào — được chen vào. Một jsonDecode mất 200 ms bên trong hàm async sẽ chặn đủ 200 ms, rắc bao nhiêu await xung quanh cũng không đổi. Cách sửa là dùng isolate thứ hai: bộ nhớ riêng, event loop riêng, chạy song song thật trên máy nhiều nhân. Phần đó dễ. Phần khiến người ta mắc kẹt là mọi thứ xung quanh nó — cái gì được phép đi qua ranh giới, vì sao một closure bắ...

Flutter isolates: what actually goes off the UI thread, and what doesn't

The most expensive misconception in Flutter performance work is that async means “on another thread.” It does not. Marking a function async changes nothing about where its body runs — every statement still executes on the isolate that called it, which in a Flutter app is almost always the UI isolate , the one that also builds your widgets and drives your animations. What await gives you is a suspension point . The function runs until the first await , hands control back to the event loop, and resumes later when the awaited future completes. Between two suspension points, your code owns the thread completely and nothing else — not a tap, not a frame — gets to run. A jsonDecode that takes 200 ms inside an async function blocks for the full 200 ms, and no amount of await sprinkled around it changes that. The fix is a second isolate: separate memory, separate event loop, real parallelism on a multi-core device. That part is easy. The part people get stuck on is everything around it...