Evan Carroll
Evan Carroll

Reputation: 1

Does #[derive(PartialEq, Eq)] increase code size?

I submitted a patch to derive-builder because I needed the ability to test failures generated. This patch enabled Eq and PartialEq so I could I test for failures using assert_eq!().

The question asked was,

My understanding is that generating unnecessary trait implementations can increase code size.

It is my understanding that implementations that are not used do not generate more code? Which of these two is correct?

Upvotes: 2

Views: 524

Answers (1)

Evan Carroll
Evan Carroll

Reputation: 1

Here is what I did to test this theory, I generated a simple binary,

#[derive(Debug)]
struct Foo {
  id: i64
}

fn main() {
  let a = Foo { id: 42 }; => Foo
  println!("Hello, world! [{} {:?}]", a.id, a);
}

I then did the same generation but with #[derive(Debug, PartialEq, Eq)]. In this, I found both generated the same hash; they were identical. Not content, I also tried creating a library and compiling with --release. Same thing. This time with just struct Foo (no main). In this case, I did observe a difference, here is the nuance:

  • Between the two runs the rlib (rust library) file had a different size.
  • An rlib is an archive. For me it had three files, one of them ended in cgu.0.rcgu.o the other in cgu.1.rcgu.o, and there was one file that was lib.rmeta.
  • Of the files in the archive, the *.o files were exactly the same (hashed).
  • The lib.rmeta file was larger in the library that also derived Eq, and PartialEq.

Now as to the merit of rmeta, the Rust documentation says this,

An rmeta file is custom binary format that contains the metadata for the crate. This file can be used for fast "checks" of a project by skipping all code generation (as is done with cargo check), collecting enough information for documentation (as is done with cargo doc), or for pipelining. This file is created if the --emit=metadata CLI option is used. rmeta files do not support linking, since they do not contain compiled object files.

So it seems something gets bigger, but that something is ONLY used for tooling purposes.

I tried the above test with the library with and without pub. I would expect if a function was generated that wasn't used it would have at the least resulted in one .o file being larger. I was not able to observe this though.

Upvotes: 2

Related Questions