[cloud_firestore]: Query snapshot events take ~8x longer to encode on iOS/macOS since the Swift migration (7.2.0), blocking the main thread
维护者通常 4 天内回复
评估
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 新手友好度
- 35/100
- Issue 类型
- 缺陷
- 描述清晰度
- 描述清楚
- 活跃度
- 活跃
- 领域
- performance
调研方向
Start with the two writers the report names: FirebaseFirestoreWriter.writeValue in FirebaseFirestoreWriter.swift and the generated FirestoreMessagesPigeonCodecWriter.writeValue in FirestoreMessages.g.swift. Run the gist's bench.sh to reproduce the 7.1.0 vs 7.2.0 timings before touching anything, and keep the Pigeon deep-equality check so the encoded output stays identical. The map fast path sits in generated code, so decide whether the real fix belongs upstream in Pigeon or in an override outside the generated file; done means timings close to 7.1.0.
由索引模型根据 Issue 内容生成。
描述
Is there an existing issue for this?
- I have searched the existing issues.
Which plugins are affected?
Other
Which platforms are affected?
iOS, macOS
Description
After upgrading cloud_firestore from 7.1.0 to 7.2.0, a snapshots() listener on a collection of more than 10,000 documents makes our iOS app (release build, iPhone 12, iOS 27.2.1) stop responding. It happens on the first load and again each time a document in the collection is written, so the app stays frozen while uploads keep adding documents.
Every query snapshot event carries all documents of the query. QuerySnapshotStreamHandler.emit passes the event to FlutterEventSink on the main queue, and FlutterEventChannel encodes it there synchronously with FirestoreMessagesPigeonCodecWriter. Because the platform and UI threads are merged by default on iOS, the Dart isolate is blocked for the same time.
The encoding itself is what got slower. For the same payload, the Swift codec in 7.2.0 takes about 8x as long as the Objective-C codec in 7.1.0:
| Documents | 7.1.0 (Objective-C) | 7.2.0 (Swift) |
|---|---|---|
| 1,000 | 34 ms | 290 ms |
| 5,000 | 169 ms | 1,425 ms |
| 10,000 | 340 ms | 2,839 ms |
| 20,000 | 675 ms | 5,678 ms |
Apple M2 Pro, macOS 27.2.1, release engine, built with optimizations. Each document has 26 or 27 fields. See the reproduction below.
The first event of a listener also carries every document a second time in documentChanges (as noted in #18878), so it takes about twice as long as the table shows.
Expected: encoding a snapshot costs about the same as in 7.1.0.
Actual: about 8x the time, all of it on the main thread.
Where the time goes
Every string and number in every document goes through FirestoreMessagesPigeonCodecWriter.writeValue, which tries 24 as? casts before calling super, and then through FirebaseFirestoreWriter.writeValue, which tries 13 more before it reaches the NSNumber branch or super.writeValue. In 7.1.0 these were isKindOfClass: checks. In Swift, casting an NSString or NSNumber held in Any to a Swift struct, enum, or bridged type (DocumentChangeType, InternalDocumentSnapshot, Date, Data, [Any], [AnyHashable: Any], ...) goes through the runtime's dynamic cast path with a protocol conformance lookup each time. On top of that, each document's data ([String?: Any?]) is copied into a new [AnyHashable: Any] by the as? [AnyHashable: Any] cast before it is written.
A sample of the benchmark while encoding is dominated by tryCast, swift_conformsToProtocolMaybeInstantiateSuperclasses, conformance cache lookups, and findBridgeWitness (see the log output below).
Reproducing the issue
In an app
- Listen to
FirebaseFirestore.instance.collection('items').snapshots()where the collection holds about 10,000 documents with about 25 string, number, and boolean fields each. - Run a release build on an iOS device.
- Write one document to the collection. The UI stops responding while the event is encoded, about 2.8 s per event going by the Mac numbers above.
Codec benchmark (no Firebase project needed)
https://gist.github.com/prsh0525/58d316dae866ce9c786301af0d01686c
Run bash bench.sh. It copies the codec sources of 7.1.0 and 7.2.0 unmodified from the pub cache and replaces only the Firebase SDK types they reference with empty classes. It links them against the FlutterMacOS release engine and builds with -O / -O2. It then encodes the same InternalQuerySnapshot (N documents, each with 13 strings, 4 or 5 integers, 2 doubles, and 7 booleans, plus one document change) with the codec that the plugin gives every FlutterEventChannel.
Firebase Core version
5.2.0
Flutter Version
3.50.1
Relevant Log Output
# sample <pid> 4 while the 7.2.0 benchmark encodes, sorted by top of stack
tryCast(swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, ...) (in libswiftCore.dylib) 301
__swift::__runtime::llvm::hashing::detail::hash_short(char const*, unsigned long, unsigned long long) (in libswiftCore.dylib) 225
swift_conformsToProtocolMaybeInstantiateSuperclasses(...) (in libswiftCore.dylib) 174
swift::ConcurrentReadableHashMap<(anonymous namespace)::ConformanceCacheEntry, swift::LazyMutex>::find<...>(...) (in libswiftCore.dylib) 108
object_getClass (in libobjc.A.dylib) 88
swift_dynamicCast (in libswiftCore.dylib) 80
_dyld_find_protocol_conformance_on_disk (in libdyld.dylib) 56
objc_opt_isKindOfClass (in libobjc.A.dylib) 56
findBridgeWitness(swift::TargetMetadata<swift::InProcess> const*) (in libswiftCore.dylib) 36
tryCastFromClassToObjCBridgeable(...) (in libswiftCore.dylib) 25
Flutter dependencies
Expand Flutter dependencies snippet
cloud_firestore: 7.2.0
cloud_firestore_platform_interface: 8.2.0
firebase_core: 5.2.0
# Firebase iOS SDK 13.2.0 through Swift Package Manager
Additional context and comments
Checking the common leaf types first in both writers, and writing the Pigeon [String?: Any?] maps directly instead of converting them to [AnyHashable: Any], recovers most of it:
| Documents | 7.1.0 (Objective-C) | 7.2.0 (Swift) | 7.2.0 + patch below |
|---|---|---|---|
| 1,000 | 34 ms | 290 ms | 64 ms |
| 10,000 | 340 ms | 2,839 ms | 634 ms |
The patched codec's output decodes to a message equal to the unpatched one (checked with the Pigeon-generated deep equality, which ignores map key order). It is still about 1.9x of 7.1.0, so the remaining collection casts may be worth a look as well. The second hunk is in generated code, so a real fix probably belongs in the Pigeon output or in an override outside the generated file.
Patch against cloud_firestore 7.2.0
--- a/FirebaseFirestoreWriter.swift
+++ b/FirebaseFirestoreWriter.swift
@@ -22,6 +22,35 @@
class FirebaseFirestoreWriter: FlutterStandardWriter {
override func writeValue(_ value: Any) {
+ if value is NSString || value is String {
+ super.writeValue(value)
+ return
+ }
+ if let number = value as? NSNumber {
+ if number == NSNumber(value: Double.infinity) {
+ writeByte(FirestoreDataType.infinity.rawValue)
+ return
+ }
+ if number == NSNumber(value: -Double.infinity) {
+ writeByte(FirestoreDataType.negativeInfinity.rawValue)
+ return
+ }
+ if number.description.lowercased() == "nan" {
+ writeByte(FirestoreDataType.nan.rawValue)
+ return
+ }
+ super.writeValue(value)
+ return
+ }
+ if let map = value as? [String?: Any?] {
+ writeByte(kStandardFieldMap)
+ writeSize(UInt32(map.count))
+ for (key, item) in map {
+ writeValue(key as Any)
+ writeValue(item as Any)
+ }
+ return
+ }
if let date = value as? Date {
writeByte(FirestoreDataType.dateTime.rawValue)
var ms = Int64(date.timeIntervalSince1970 * 1000.0)
--- a/FirestoreMessages.g.swift
+++ b/FirestoreMessages.g.swift
@@ -1129,6 +1129,10 @@
class FirestoreMessagesPigeonCodecWriter: FirebaseFirestoreWriter {
override func writeValue(_ value: Any) {
+ if value is NSString || value is NSNumber || value is String {
+ super.writeValue(value)
+ return
+ }
if let value = value as? DocumentChangeType {
super.writeByte(129)
super.writeValue(value.rawValue)
Related: #18607 (the Swift migration), #18878 (reuses converted documents in query snapshots; the codec still writes each changed document twice).
- 主要语言
- Dart
- 星标
- 9.3k
- 派生
- 4.1k
- 平均合并
- 4 天 17 小时
- 30 天内合并 PR
- 49
环境准备
- 没有 Dockerfile 或 Docker Compose 文件
- 有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
firebase/flutterfire 的其他 Issue
-
[cloud_functions]: Apple platforms ignore custom domains passed as region可能已有人在做 @ragavendranbala-TSL 今天认领。 未关闭Needs Attention platform: ios platform: macos plugin: functions type: bug
难度 2/5 1-3 小时 新手友好度 78/100
firebase/flutterfire#19015 · 2 条评论 ·
维护者通常 4 天内回复
-
Needs Attention platform: android plugin: messaging type: bug
难度 4/5 3-5 天 新手友好度 45/100
firebase/flutterfire#19017 ·
维护者通常 4 天内回复
-
Needs Attention platform: web plugin: crashlytics type: enhancement
难度 5/5 一周以上 新手友好度 34/100
firebase/flutterfire#19014 · 1 条评论 ·
维护者通常 4 天内回复
-
[firebase_messaging]: Android getToken() errors lose their cause since firebase-messaging 25.1.0 ("FCM Registration failed!")可能已有人在做 @SelaseKay 于 3 天前认领。 未关闭Needs Attention platform: android plugin: messaging reproduced type: bug
难度 4/5 3-5 天 新手友好度 22/100
firebase/flutterfire#18997 · 1 条评论 ·
维护者通常 4 天内回复
-
[firebase_storage]: Windows: getData() crashes with access violation (use-after-free of StorageReference in ReferenceGetData)可能已有人在做 @SelaseKay 于 4 天前认领。 未关闭blocked: customer-response platform: windows plugin: storage type: bug type: crash
难度 4/5 3-5 天 新手友好度 35/100
firebase/flutterfire#18994 · 2 条评论 ·
维护者通常 4 天内回复
查看 firebase/flutterfire 的全部 Issue
相似的 Issue
-
feature
难度 2/5 1-3 小时 新手友好度 76/100
VeryGoodOpenSource/vgv-ai-flutter-plugin#219 · 1 条评论 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 82/100
Anxcye/anx-reader#1024 ·
-
难度 2/5 1-3 小时 新手友好度 78/100
RevenueCat/purchases-flutter#2048 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 84/100
Baseflow/flutter-geocoding#337 · 1 个 reaction ·
维护者通常 1 天内回复
-
bug
难度 2/5 1-3 小时 新手友好度 72/100
hajisensai/Fushi#4543 · 3 条评论 ·
维护者通常 1 天内回复