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

Aperta
#18,991 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 4 giorni

@SelaseKay ci sta già lavorando.

Dal 23/11/2026.

  • #18995 di @SelaseKay — aperta

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
35/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
dart, swift
Ambito
performance

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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).

Lingua principale
Dart
Stelle
9.3k
Fork
4.1k
Merge medio
4g 17h
PR unite (30g)
49

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di firebase/flutterfire

Tutte le issue di firebase/flutterfire

Issue simili

Altre issue su Dart

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.