Skip to content

Commit abe6480

Browse files
Precompute size
1 parent 50318f2 commit abe6480

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

Firestore/Source/API/FSTUserDataReader.mm

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -328,38 +328,39 @@ - (FieldValue)parsedQueryValue:(id)input allowArrays:(bool)allowArrays {
328328

329329
- (google_firestore_v1_Value)parseDictionary:(NSDictionary<NSString *, id> *)dict
330330
context:(ParseContext &&)context {
331-
google_firestore_v1_Value result{};
331+
__block google_firestore_v1_Value result{};
332332
result.which_value_type = google_firestore_v1_Value_map_value_tag;
333333

334-
__block std::vector<google_firestore_v1_MapValue_FieldsEntry> fields;
335-
336334
if (dict.count == 0) {
337335
const FieldPath *path = context.path();
338336
if (path && !path->empty()) {
339337
context.AddToFieldMask(*path);
340338
}
341339
} else {
342-
// Populate a vector of fields since we don't know the size of the final fields array.
340+
// Compute the final size of the fields array, which contains an entry for
341+
// all fields that are not FieldValue sentinels
342+
__block pb_size_t count = 0;
343+
[dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *) {
344+
if (![value isKindOfClass:[FIRFieldValue class]]) {
345+
++count;
346+
}
347+
}];
348+
349+
result.map_value.fields_count = count;
350+
result.map_value.fields = nanopb::MakeArray<google_firestore_v1_MapValue_FieldsEntry>(count);
351+
352+
__block pb_size_t index = 0;
343353
[dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *) {
344354
absl::optional<google_firestore_v1_Value> parsedValue =
345355
[self parseData:value context:context.ChildContext(util::MakeString(key))];
346356
if (parsedValue) {
347357
google_firestore_v1_MapValue_FieldsEntry fieldsEntry;
348-
fieldsEntry.key = nanopb::MakeBytesArray(util::MakeString(key));
349-
fieldsEntry.value = *parsedValue;
350-
fields.push_back(fieldsEntry);
358+
result.map_value.fields[index].key = nanopb::MakeBytesArray(util::MakeString(key));
359+
result.map_value.fields[index].value = *parsedValue;
351360
}
352361
}];
353362
}
354363

355-
result.map_value.fields_count = static_cast<pb_size_t>(fields.size());
356-
result.map_value.fields =
357-
nanopb::MakeArray<google_firestore_v1_MapValue_FieldsEntry>(result.map_value.fields_count);
358-
359-
for (size_t i = 0; i < fields.size(); ++i) {
360-
result.map_value.fields[i] = fields[i];
361-
}
362-
363364
return result;
364365
}
365366

0 commit comments

Comments
 (0)