You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fory.apache.org by ch...@apache.org on 2026/10/04 09:16:18 UTC

(fory) branch main updated: perf(cpp): serialize forward_list without a temporary vector (#4113)

This is an automated email from the ASF dual-hosted git repository.

chaokunyang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fory.git


The following commit(s) were added to refs/heads/main by this push:
     new 61d406317 perf(cpp): serialize forward_list without a temporary vector (#4113)
61d406317 is described below

commit 61d4063177f5cf6b2bcbaefedcaafa1083db0f16
Author: Chang-Yen (Brian) Li <b0...@csie.ntu.edu.tw>
AuthorDate: Sun Oct 4 04:16:13 2026 -0500

    perf(cpp): serialize forward_list without a temporary vector (#4113)
    
    <!--
    **Thanks for contributing to Apache Fory™.**
    
    **If this is your first time opening a PR on fory, you can refer to
    [CONTRIBUTING.md](https://github.com/apache/fory/blob/main/CONTRIBUTING.md).**
    
    Contribution Checklist
    
    - The **Apache Fory™** community has requirements on the naming of PR
    titles. You can also find instructions in
    [CONTRIBUTING.md](https://github.com/apache/fory/blob/main/CONTRIBUTING.md).
    
    - Apache Fory™ has a strong focus on performance. If the PR you submit
    will have an impact on performance, benchmark it first and provide the
    benchmark result here.
    -->
    
    ## Why?
    
    The collection wire format requires the element count before the
    elements are written, but `std::forward_list` has no `size()` method.
    Its generic serializer previously worked around this by collecting
    element references in a temporary vector and then serializing from that
    vector. Growing the vector introduces repeated heap allocations and
    moves of existing reference entries, even though serialization only
    needs the count and access to the original elements. A counting pass
    followed by direct serialization avoids this temporary storage and its
    allocation overhead.
    
    The generic serializer also duplicated the shared fast collection
    writer's header, type-information, null-handling, and element-writing
    logic. Passing the counted length to the shared writers lets
    `forward_list` reuse the existing collection encoding instead of
    maintaining a separate copy of the fast path.
    
    ## What does this PR do?
    
    The shared collection writers now accept an explicit length, allowing
    them to serialize containers that have no `size()` method. The
    `forward_list` serialization path becomes:
    
    1. `write()` calls `write_data_generic()`, which traverses the list to
    count its elements and checks that the count fits in `uint32_t`.
    2. For non-polymorphic, non-shared-reference elements, it calls
    `write_collection_data_fast()` with the original list and the computed
    length. This replaces the duplicated fast-path logic previously embedded
    in `write_data_generic()`; the shared writer now handles the collection
    header, element type information, null flags, and element serialization.
    3. For polymorphic or shared-reference elements, it calls
    `write_collection_data_slow()` with the original list and the computed
    length. That writer retains its existing runtime-type, null, and
    reference handling while iterating directly over the list.
    
    Both paths serialize from the original `forward_list`, eliminating the
    temporary vector and the helper that unwrapped its `reference_wrapper`
    entries. Containers with `size()` continue to obtain their length from
    `size()` and delegate to the same writers, with a `uint32_t` range check
    before writing the length. The wire format and public API are unchanged.
    
    Added wire-equivalence coverage for non-nullable strings, nullable
    scalar elements, and shared-reference elements. The full C++
    serialization suite passes: 14 test targets.
    
    ## Related issues
    
    None known.
    
    ## AI Contribution Checklist
    
    <!-- Full requirements and disclosure template:
    
    https://github.com/apache/fory/blob/main/AI_POLICY.md#9-contributor-checklist-for-ai-assisted-prs
    
    The checklist below is intentionally left unanswered for the contributor
    to complete.
    -->
    
    - [x] Substantial AI assistance was used in this PR: `yes`
    - [x] If `yes`, I included the standardized `AI Usage Disclosure` block
    below.
    - [x] If `yes`, I can explain and defend all important changes without
    AI help.
    - [x] If `yes`, I reviewed AI-assisted code changes line by line before
    submission.
    - [x] If `yes`, I completed line-by-line self-review first and fixed
    issues before requesting AI review.
    - [x] If `yes`, I ran two fresh AI review agents on the current PR diff
    or current HEAD after the latest code changes: one Fory-guided reviewer
    using `AGENTS.md` and `.agents/ci-and-pr.md`, and one independent
    general reviewer in a separate clean-context review session that was not
    pointed to `.agents/ci-and-pr.md` or any copied Fory-specific review
    checklist. If the independent reviewer's tooling auto-loaded
    `AGENTS.md`, it followed the independent-review carve-out there.
    - [x] If `yes`, I addressed all AI review comments and repeated the
    review loop until both AI reviewers reported no further actionable
    comments.
    - [x] If `yes`, I attached screenshot evidence or equivalent persisted
    links of the final clean AI review results from both fresh reviewers on
    the current PR diff or current HEAD after the latest code changes in
    this PR body.
    - [artifact1.md — Fory-guided
    review](https://gist.github.com/BrianLii/025b16a4368678d81f77d5bae6396965)
    - [artifact2.md — Independent
    review](https://gist.github.com/BrianLii/bc8b9c269df99220a6fcd636cbdfb1f7)
    - [x] If `yes`, I ran adequate human verification and recorded evidence
    (checks run locally or in CI, pass/fail summary, and confirmation I
    reviewed results).
    - [x] If `yes`, I added or updated tests and specs where required.
    - [x] If `yes`, I validated protocol and performance impacts with
    evidence when applicable.
    - [x] If `yes`, I verified licensing and provenance compliance.
    
    AI Usage Disclosure (only when substantial AI assistance = `yes`):
    
    ```text
    AI Usage Disclosure
    - substantial_ai_assistance: <yes or no>
    - scope: code drafting, refactor suggestions, tests
    - affected_files_or_subsystems: <high-level paths/modules>
    - ai_review: Two fresh reviewers (one Fory-guided and one independent) reviewed the current HEAD; both reported no actionable findings.
    - ai_review_artifacts: linked in the checklist above
    - human_verification: checked the unit tests and the benchmark results locally
    - performance_verification: benchmark result provided in the PR description
    - provenance_license_confirmation: no incompatible third-party code introduced
    ```
    
    ## Does this PR introduce any user-facing change?
    
    No public API or binary protocol changes.
    
    - [ ] Does this PR introduce any public API change?
    - [ ] Does this PR introduce any binary protocol compatibility change?
    
    ## Benchmark
    
    Release C++17 benchmark on Darwin arm64 with AppleClang 21.0.0. Each
    process serializes a prebuilt 1,024-element `std::forward_list<int64_t>`
    into a reused output buffer reserved to 65,536 bytes. It uses
    `Fory::builder().xlang(true).compatible(true).track_ref(false)` and
    performs 1,000 warmup serializations before measurement. Each latency
    result is the median of nine samples, with 10,000 serializations per
    sample. Four baseline/change process pairs were run consecutively.
    
    | Pair | Base `8acb8ca7` |         Change | Change |
    | ---: | --------------: | -------------: | -----: |
    |    1 |  2,698.84 ns/op | 2,459.49 ns/op |  -8.9% |
    |    2 |  2,745.90 ns/op | 2,408.87 ns/op | -12.3% |
    |    3 |  2,605.29 ns/op | 2,335.52 ns/op | -10.4% |
    |    4 |  2,692.01 ns/op | 2,395.23 ns/op | -11.0% |
    
    The full C++ serialization suite passed: 14 test targets.
---
 cpp/fory/serialization/collection_serializer.h     | 158 ++++++---------------
 .../serialization/collection_serializer_test.cc    |  31 ++++
 2 files changed, 77 insertions(+), 112 deletions(-)

diff --git a/cpp/fory/serialization/collection_serializer.h b/cpp/fory/serialization/collection_serializer.h
index bafe03a46..8d3d40bdc 100644
--- a/cpp/fory/serialization/collection_serializer.h
+++ b/cpp/fory/serialization/collection_serializer.h
@@ -26,7 +26,6 @@
 #include <cstring>
 #include <deque>
 #include <forward_list>
-#include <functional>
 #include <limits>
 #include <list>
 #include <set>
@@ -148,16 +147,16 @@ read_collection_element_type_info(ReadContext &ctx) {
 /// write collection data for non-polymorphic, non-shared-ref elements.
 template <typename T, typename Container>
 inline void write_collection_data_fast(const Container &coll, WriteContext &ctx,
-                                       bool has_generics) {
+                                       bool has_generics, uint32_t length) {
   static_assert(!is_polymorphic_v<T>,
                 "Fast path is for non-polymorphic types only");
   static_assert(!is_shared_ref_v<T>,
                 "Fast path is for non-shared-ref types only");
 
   // write length
-  ctx.write_var_uint32(static_cast<uint32_t>(coll.size()));
+  ctx.write_var_uint32(length);
 
-  if (coll.empty()) {
+  if (length == 0) {
     return;
   }
 
@@ -236,24 +235,26 @@ inline void write_collection_data_fast(const Container &coll, WriteContext &ctx,
   }
 }
 
-template <typename T, typename Elem>
-FORY_ALWAYS_INLINE const T &collection_value(const Elem &elem) {
-  if constexpr (std::is_same_v<std::decay_t<Elem>,
-                               std::reference_wrapper<const T>>) {
-    return elem.get();
-  } else {
-    return elem;
+template <typename T, typename Container>
+inline void write_collection_data_fast(const Container &coll, WriteContext &ctx,
+                                       bool has_generics) {
+  const uint64_t size = coll.size();
+  if (FORY_PREDICT_FALSE(size > std::numeric_limits<uint32_t>::max())) {
+    ctx.set_error(Error::invalid("Collection size exceeds uint32_t range"));
+    return;
   }
+  write_collection_data_fast<T>(coll, ctx, has_generics,
+                                static_cast<uint32_t>(size));
 }
 
 /// write collection data for polymorphic or shared-ref elements.
 template <typename T, typename Container>
 inline void write_collection_data_slow(const Container &coll, WriteContext &ctx,
-                                       bool has_generics) {
+                                       bool has_generics, uint32_t length) {
   // write length
-  ctx.write_var_uint32(static_cast<uint32_t>(coll.size()));
+  ctx.write_var_uint32(length);
 
-  if (coll.empty()) {
+  if (length == 0) {
     return;
   }
 
@@ -273,7 +274,7 @@ inline void write_collection_data_slow(const Container &coll, WriteContext &ctx,
   bool first_type_set = false;
 
   for (const auto &raw_elem : coll) {
-    const T &elem = collection_value<T>(raw_elem);
+    const T &elem = raw_elem;
     // Check for nulls
     if constexpr (is_nullable_v<T>) {
       if (is_null_value(elem)) {
@@ -359,7 +360,7 @@ inline void write_collection_data_slow(const Container &coll, WriteContext &ctx,
     if (tracking_refs) {
       // Track refs - write ref flag per element per xlang spec
       for (const auto &raw_elem : coll) {
-        const T &elem = collection_value<T>(raw_elem);
+        const T &elem = raw_elem;
         if constexpr (elem_is_polymorphic && elem_is_smart_ptr) {
           Serializer<T>::write_with_data(elem, ctx, RefMode::Tracking,
                                          elem_writer, has_generics);
@@ -371,7 +372,7 @@ inline void write_collection_data_slow(const Container &coll, WriteContext &ctx,
     } else if (!has_null) {
       // No nulls, no ref tracking - write data directly without null flag
       for (const auto &raw_elem : coll) {
-        const T &elem = collection_value<T>(raw_elem);
+        const T &elem = raw_elem;
         if constexpr (elem_is_polymorphic && elem_is_smart_ptr) {
           Serializer<T>::write_with_data(elem, ctx, RefMode::None, elem_writer,
                                          has_generics);
@@ -392,7 +393,7 @@ inline void write_collection_data_slow(const Container &coll, WriteContext &ctx,
     } else {
       // Has null elements - write with null flag
       for (const auto &raw_elem : coll) {
-        const T &elem = collection_value<T>(raw_elem);
+        const T &elem = raw_elem;
         if constexpr (elem_is_polymorphic && elem_is_smart_ptr) {
           Serializer<T>::write_with_data(elem, ctx, RefMode::NullOnly,
                                          elem_writer, has_generics);
@@ -407,25 +408,37 @@ inline void write_collection_data_slow(const Container &coll, WriteContext &ctx,
     if (tracking_refs) {
       // Track refs - write ref flag + type info per element
       for (const auto &raw_elem : coll) {
-        const T &elem = collection_value<T>(raw_elem);
+        const T &elem = raw_elem;
         Serializer<T>::write(elem, ctx, RefMode::Tracking, true, has_generics);
       }
     } else if (!has_null) {
       // No nulls - write without null flag (RefMode::None)
       for (const auto &raw_elem : coll) {
-        const T &elem = collection_value<T>(raw_elem);
+        const T &elem = raw_elem;
         Serializer<T>::write(elem, ctx, RefMode::None, true, has_generics);
       }
     } else {
       // Has null elements - write with null flag (RefMode::NullOnly)
       for (const auto &raw_elem : coll) {
-        const T &elem = collection_value<T>(raw_elem);
+        const T &elem = raw_elem;
         Serializer<T>::write(elem, ctx, RefMode::NullOnly, true, has_generics);
       }
     }
   }
 }
 
+template <typename T, typename Container>
+inline void write_collection_data_slow(const Container &coll, WriteContext &ctx,
+                                       bool has_generics) {
+  const uint64_t size = coll.size();
+  if (FORY_PREDICT_FALSE(size > std::numeric_limits<uint32_t>::max())) {
+    ctx.set_error(Error::invalid("Collection size exceeds uint32_t range"));
+    return;
+  }
+  write_collection_data_slow<T>(coll, ctx, has_generics,
+                                static_cast<uint32_t>(size));
+}
+
 // Helper trait to detect if container has push_back
 template <typename Container, typename T, typename = void>
 struct has_push_back : std::false_type {};
@@ -2122,104 +2135,25 @@ struct Serializer<std::forward_list<T, Alloc>> {
 
   static inline void write_data_generic(const std::forward_list<T, Alloc> &lst,
                                         WriteContext &ctx, bool has_generics) {
-    // Convert to vector first for efficient writing (forward_list has no size)
-    std::vector<std::reference_wrapper<const T>> temp;
+    // forward_list has no size(), so count elements before writing the header.
+    uint64_t size = 0;
     for (const auto &elem : lst) {
-      temp.push_back(std::cref(elem));
+      (void)elem;
+      ++size;
     }
-
-    // Dispatch to fast or slow path based on element type characteristics
-    constexpr bool is_fast_path = !is_polymorphic_v<T> && !is_shared_ref_v<T>;
-
-    if constexpr (!is_fast_path) {
-      write_collection_data_slow<T>(temp, ctx, has_generics);
+    if (FORY_PREDICT_FALSE(size > std::numeric_limits<uint32_t>::max())) {
+      ctx.set_error(Error::invalid("forward_list size exceeds uint32_t range"));
       return;
     }
+    const uint32_t length = static_cast<uint32_t>(size);
 
-    // write length
-    ctx.write_var_uint32(static_cast<uint32_t>(temp.size()));
-
-    if (temp.empty()) {
-      return;
-    }
+    // Dispatch to fast or slow path based on element type characteristics
+    constexpr bool is_fast_path = !is_polymorphic_v<T> && !is_shared_ref_v<T>;
 
     if constexpr (is_fast_path) {
-      // Check for null elements
-      bool has_null = false;
-      if constexpr (is_nullable_v<T>) {
-        for (const auto &elem_ref : temp) {
-          if (is_null_value(elem_ref.get())) {
-            has_null = true;
-            break;
-          }
-        }
-      }
-
-      // Build header bitmap
-      uint8_t bitmap = COLL_IS_SAME_TYPE;
-      if (has_null) {
-        bitmap |= COLL_HAS_NULL;
-      }
-
-      // Determine if element type is declared
-      using ElemType = nullable_element_t<T>;
-      bool is_elem_declared =
-          has_generics && !need_type_for_collection_elem<ElemType>();
-      if (is_elem_declared) {
-        bitmap |= COLL_DECL_ELEMENT_TYPE;
-      }
-
-      // write header
-      ctx.write_uint8(bitmap);
-
-      // write element type info if not declared
-      if (!is_elem_declared) {
-        Serializer<ElemType>::write_type_info(ctx);
-      }
-
-      // write elements
-      if constexpr (is_nullable_v<T>) {
-        using Inner = nullable_element_t<T>;
-        if (has_null) {
-          for (const auto &elem_ref : temp) {
-            const auto &elem = elem_ref.get();
-            if (is_null_value(elem)) {
-              ctx.write_int8(NULL_FLAG);
-            } else {
-              ctx.write_int8(NOT_NULL_VALUE_FLAG);
-              if (is_elem_declared) {
-                Serializer<Inner>::write_data(deref_nullable(elem), ctx);
-              } else {
-                Serializer<Inner>::write(deref_nullable(elem), ctx,
-                                         RefMode::None, false);
-              }
-            }
-          }
-        } else {
-          for (const auto &elem_ref : temp) {
-            const auto &elem = elem_ref.get();
-            if (is_elem_declared) {
-              Serializer<Inner>::write_data(deref_nullable(elem), ctx);
-            } else {
-              Serializer<Inner>::write(deref_nullable(elem), ctx, RefMode::None,
-                                       false);
-            }
-          }
-        }
-      } else {
-        for (const auto &elem_ref : temp) {
-          const auto &elem = elem_ref.get();
-          if (is_elem_declared) {
-            if constexpr (is_generic_type_v<T>) {
-              Serializer<T>::write_data_generic(elem, ctx, true);
-            } else {
-              Serializer<T>::write_data(elem, ctx);
-            }
-          } else {
-            Serializer<T>::write(elem, ctx, RefMode::None, false);
-          }
-        }
-      }
+      write_collection_data_fast<T>(lst, ctx, has_generics, length);
+    } else {
+      write_collection_data_slow<T>(lst, ctx, has_generics, length);
     }
   }
 
diff --git a/cpp/fory/serialization/collection_serializer_test.cc b/cpp/fory/serialization/collection_serializer_test.cc
index 489042891..70151ceb2 100644
--- a/cpp/fory/serialization/collection_serializer_test.cc
+++ b/cpp/fory/serialization/collection_serializer_test.cc
@@ -710,6 +710,37 @@ TEST(CollectionSerializerTest, ForwardListIntRoundTrip) {
   EXPECT_EQ(result[4], 500);
 }
 
+TEST(CollectionSerializerTest, ForwardListWireMatchesVector) {
+  auto fory =
+      Fory::builder().xlang(true).compatible(false).track_ref(false).build();
+
+  std::forward_list<std::string> linked_strings{"first", "second"};
+  std::vector<std::string> vector_strings{"first", "second"};
+  auto linked_strings_bytes = fory.serialize(linked_strings);
+  auto vector_strings_bytes = fory.serialize(vector_strings);
+  ASSERT_TRUE(linked_strings_bytes.ok());
+  ASSERT_TRUE(vector_strings_bytes.ok());
+  EXPECT_EQ(linked_strings_bytes.value(), vector_strings_bytes.value());
+
+  std::forward_list<std::optional<int32_t>> linked_optional{1, std::nullopt, 3};
+  std::vector<std::optional<int32_t>> vector_optional{1, std::nullopt, 3};
+  auto linked_optional_bytes = fory.serialize(linked_optional);
+  auto vector_optional_bytes = fory.serialize(vector_optional);
+  ASSERT_TRUE(linked_optional_bytes.ok());
+  ASSERT_TRUE(vector_optional_bytes.ok());
+  EXPECT_EQ(linked_optional_bytes.value(), vector_optional_bytes.value());
+
+  auto first = std::make_shared<std::string>("first");
+  auto second = std::make_shared<std::string>("second");
+  std::forward_list<std::shared_ptr<std::string>> linked_shared{first, second};
+  std::vector<std::shared_ptr<std::string>> vector_shared{first, second};
+  auto linked_shared_bytes = fory.serialize(linked_shared);
+  auto vector_shared_bytes = fory.serialize(vector_shared);
+  ASSERT_TRUE(linked_shared_bytes.ok());
+  ASSERT_TRUE(vector_shared_bytes.ok());
+  EXPECT_EQ(linked_shared_bytes.value(), vector_shared_bytes.value());
+}
+
 TEST(CollectionSerializerTest, ForwardListEmptyRoundTrip) {
   auto fory = Fory::builder().xlang(true).compatible(false).build();
   fory.register_struct<ForwardListStringHolder>(502);


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org