Home > database >  Speed of comparing structs using derive(Eq) versus derive(Serialize)
Speed of comparing structs using derive(Eq) versus derive(Serialize)

Time:01-04

I was curious about how much faster it is to call Eq::eq to compare two large vectors, versus serializing both vectors to a string and comparing the output strings.

I've done a basic speed-test here: https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=73fc1cc61873fa70566eb7b2bf0793f9

The results, in release-mode, for a vector of 100 thousand simple structs:

  1. Comparing by Eq::eq(x, y): 20ms
  2. Comparing by serde_json::to_value(x) == serde_json::to_value(y): 172ms
  3. Comparing by serde_json::to_string(x) == serde_json::to_string(y): 34ms

These results surprise me a bit; I did not expect that serializing all the way to a string would be nearly as fast as the derived implementation of Eq::eq.

Is my speed-test flawed in some way? If not, what would explain why there is not a speed advantage to the Eq::eq(x, y) approach, given that it seems like it should have a lot less work to do?

CodePudding user response:

It is vec.clone()

https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=8f5badd5e2d1b7258eda6b384acd9205

The results after passing references: Times. 1:1 2:127 3:39

  • Related