Last active
April 30, 2023 09:11
-
-
Save alifgiant/42bb081a8be4873c96c09c8dd9bad9eb to your computer and use it in GitHub Desktop.
Testing Isolate Perf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'dart:isolate'; | |
void main() async { | |
const jsonStr = '{' | |
'"name": "alif",' | |
'"age": 26,' | |
'"gender": "male",' | |
'"office": "work from home"' | |
'}'; | |
const testN = 100; | |
Future asyncRun<Q>(Function(Q) function, Q message) async { | |
function(message); | |
} | |
final stopwatchA = Stopwatch()..start(); | |
for (var i = 0; i < testN; i++) { | |
jsonDecode(jsonStr); | |
} | |
print('$testN sync run : ${stopwatchA.elapsed}'); | |
final stopwatchB = Stopwatch()..start(); | |
await Future.wait( | |
[for (var i = 0; i < testN; i++) asyncRun(jsonDecode, jsonStr)], | |
); | |
print('$testN async run : ${stopwatchB.elapsed}'); | |
final stopwatchC = Stopwatch()..start(); | |
await Future.wait( | |
[for (var i = 0; i < testN; i++) Isolate.spawn(jsonDecode, jsonStr)], | |
); | |
print('$testN isolate.spawn: ${stopwatchC.elapsed}'); | |
} |
hi @nikhil-RGB , what i learned from my experiment on using isolates:
- secondary isolate is slower than the main isolate in executing codes.
- creating new isolate for every task is slower than using only small number of isolate.
compute(..)
function is creating a new isolate every time you called it.- Async execution is actually still run on main isolate (so it's faster), but it could postpone task on every
await
to unblock UI.so my recommendation for your case is: if the task that you need to run for every 50ms is short live, like simple addition or boolean check, you should definitely use async/await only. but, if the task is long running like doing heavy computation such as image processing you need to use Isolate, but try to maintain only small number of it.
Yes, thank you for the response!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi @nikhil-RGB , what i learned from my experiment on using isolates:
compute(..)
function is creating a new isolate every time you called it.await
to unblock UI.so my recommendation for your case is:
if the task that you need to run for every 50ms is short live, like simple addition or boolean check, you should definitely use async/await only. but, if the task is long running like doing heavy computation such as image processing you need to use Isolate, but try to maintain only small number of it.