[cloud_firestore]: Query snapshot events take ~8x longer to encode on iOS/macOS since the Swift migration (7.2.0), blocking the main thread

オープン
#18,991 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 4 日以内に返信

@SelaseKay がすでに取り組んでいます。

2026年11月23日 から。

  • #18995 @SelaseKay による — オープン

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
35/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
dart, swift
領域
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 の本文から書いたものです。

説明

Needs Attention platform: ios platform: macos plugin: cloud_firestore reproduced type: bug
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

  1. Listen to FirebaseFirestore.instance.collection('items').snapshots() where the collection holds about 10,000 documents with about 25 string, number, and boolean fields each.
  2. Run a release build on an iOS device.
  3. 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時間
マージ済み PR(30日)
49

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

firebase/flutterfire のほかの issue

firebase/flutterfire の issue をすべて見る

似ている issue

Dart の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。