gpt4 book ai didi

flutter - 为大量听众优化的 ChangeNotifier 的替代方案?

转载 作者:行者123 更新时间:2023-12-04 10:50:15 24 4
gpt4 key购买 nike

ChangeNotifier 的 flutter 文档说

ChangeNotifier is optimized for small numbers (one or two) of listeners. It is O(N) for adding and removing listeners and O(N²) for dispatching notifications (where N is the number of listeners).



如果我想设计一个有很多听众(例如几十个听众)的模型,是否有可供在 Flutter 中使用的替代类?

理想情况下,我正在寻找小于 O(N^2) 的东西来发送通知,其中 N 是监听器的数量。

最佳答案

有趣的是,当我查看最新的代码/文档时,它现在已经优化了!
它说(2021.01):

It is O(1) for adding listeners and O(N) for removing listeners and dispatching notifications (where N is the number of listeners).


这样我们就可以愉快地使用它了。是的!
为什么会发生这种情况:查看源代码
  void notifyListeners() {
assert(_debugAssertNotDisposed());
if (_listeners!.isEmpty)
return;

final List<_ListenerEntry> localListeners = List<_ListenerEntry>.from(_listeners!);

for (final _ListenerEntry entry in localListeners) {
try {
if (entry.list != null)
entry.listener();
} catch (exception, stack) {
...
}
}
}
我们看到它遍历监听器并调用它们。
在过去,甚至说 flutter 1.21, source code好像:
  void notifyListeners() {
assert(_debugAssertNotDisposed());
if (_listeners != null) {
final List<VoidCallback> localListeners = List<VoidCallback>.from(_listeners!);
for (final VoidCallback listener in localListeners) {
try {
if (_listeners!.contains(listener))
listener();
} catch (exception, stack) {
...
}
}
}
}
因此你看,在过去有双循环(一个 for 循环 + 一个包含检查),而在新的日子里没有。

关于flutter - 为大量听众优化的 ChangeNotifier 的替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com