dart:io sync vs async file operations
1,279
Let me try to summarize an answer based on the comments to my question. Correct me where I'm wrong.
- Running code in an
async
method doesn't make it run on another thread. - Dart is a single threaded system.
- Code gets run on an event loop.
- Performing long running synchronous tasks will block the system whether it is in an async method or not.
- An isolate is a single thread.
- If you want to run tasks on another thread then you need to run it on another isolate.
- Starting another isolate is called spawning the isolate.
- There are a few options for running tasks on another isolate including
compute
andIsolateChannel
and writing your own isolate communication code. - For File IO, the synchronous versions are faster than the asynchronous versions.
- For heavy File IO, prefer the asynchronous version because they work on a separate thread.
- For light File IO (like
file.exists()
?), using the synchronous version is an option since it is likely to be fast.
Further reading
- Isolates and Event Loops
- Single Thread Dart, What? — Part 1
- Single Thread Dart, What? — Part 2
- avoid_slow_async_io lint
Comments
-
Suragch over 1 year
There are a number of sync and async operations for files in
dart:io
:-
file.deleteSync()
andfile.delete()
-
file.readAsStringSync()
andfile.readAsString()
-
file.writeAsBytesSync(bytes)
andfile.writeAsBytes(bytes)
- and many, many more.
What are the considerations that I should keep in mind when choosing between the sync and async options? I seem to recall seeing somewhere that the sync option is faster if you have to wait for it to finish anyway (
await file.delete()
for example). But I can't remember where I saw that or if it is true.Is there any difference between this method:
Future deleteFile(File file) async { await file.delete(); print('deleted'); }
and this method:
Future deleteFile(File file) async { file.deleteSync(); print('deleted'); }
-