Open
Description
This tracker is for issues related to:
- Dart VM
Description
We should be able to transfer any object over SendPort in constant time if we know:
- Isolates share a heap
- There is one reference to an object
- The object is never used again after it is sent to a SendPort
To make this possible I propose we add a new class called Unique
that when constructed sent over a SendPort
asserts that there is one reference to each object in the object graph and nulls out its reference. That way we can have constant-time communication of any object over SendPort
s. It isn't asserted at compile time, but this might be the best we can do with Dart.
The printed timestamps should almost be the same, today the difference is 12s locally:
// @dart=2.12
import 'dart:isolate';
class Unique<T> {
T? get value => _value;
T? _value;
Unique(this._value) {
// Crawl through the object tree and ensure there is only one reference to
// each object, otherwise throw exception.
// assert(isUnique(_value));
}
}
Map<String, Object> makeLargeMap(int n) {
Map<String, Object> result = {};
for (int i = 0; i < n; ++i) {
result[i.toString()] = i;
}
return result;
}
void isolateMain(SendPort sendPort) {
ReceivePort receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
receivePort.listen((message) {
var foo = Unique<Map<String, Object>>(makeLargeMap(message));
print(DateTime.now().millisecondsSinceEpoch);
sendPort.send(foo);
// assert(foo.value == null);
});
}
void main() async {
ReceivePort receivePort = ReceivePort();
Isolate.spawn(isolateMain, receivePort.sendPort);
SendPort sendPort = await receivePort.first;
sendPort.send(10000000);
print(await receivePort.first);
print(DateTime.now().millisecondsSinceEpoch);
}
Related language request for move semantics: dart-lang/language#2355 (this has compile time checks for uniqueness)
cc @mkustermann
Alternatives considered
- TransferableTypedData - this requires encoding and decoding time for most datatypes
- Isolate.exit - this requires you to spawn an isolate for each result