flatbuffers icon indicating copy to clipboard operation
flatbuffers copied to clipboard

[Rust] `FlatBufferBuilder::create_shared_string` is O(N^2)

Open PollRobots opened this issue 1 year ago • 3 comments

The string_pool is maintained as a sorted list of offsets, which when create_shared_string is called are searched using slice::binary_search_by

If a match is not found, then the string is stored using create_byte_string and the index is inserted into string_pool using Vec::insert

So the happy path is an O(LogN) binary search

The unhappy path is an O(N) vector insertion

Every happy path requires a preceding unhappy path, so if you have N unique strings and M duplicates, then the cost of all calls to create_shared_string becomes O(N^2) + O(MLogN) or simply O(N^2)

I have a stress test that is writing a flatbuffer with ~500,000 unique strings, 80% of our serialization time is in create_shared_string

I can reduce this to ~30% of our serialization time (total serialization time goes from to 20.4s to 4.1s) by

  1. changing the type of string_pool to HashMap<String, WIPOffset<&'fbb str>>, and
  2. changing the implementation of create_shared_string to
    #[inline]
    pub fn create_shared_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str> {
        self.assert_not_nested(
            "create_shared_string can not be called when a table or vector is under construction",
        );

        match self.strings_pool.get(s) {
            Some(address) => address,
            None => {
                let address = WIPOffset::new(self.create_byte_string(s.as_bytes()).value());
                self.strings_pool.insert(s.to_owned(), address);
                address
            }
        }
    }

PollRobots avatar Sep 04 '25 01:09 PollRobots

this sounds like a great analysis and change -- I don't think we have any rust afficionados helping out at the moment, so:

  1. is this in any way a breaking change to any users?
  2. would you be up for creating a PR for this optimization?
  3. if so, could you please add a test to ensure the functionality of create_shared_string remains the same?

Thanks!

jtdavis777 avatar Dec 06 '25 05:12 jtdavis777

@jtdavis777 Can I work on this? I'd like to contribute. I can provide solution soon. could you assign me? thanks

statxc avatar Mar 06 '26 19:03 statxc

sure, sounds good.

jtdavis777 avatar Mar 06 '26 20:03 jtdavis777