Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What is the reason for C-RW-VALUE? #174

Closed
tbu- opened this issue Jul 3, 2018 · 4 comments
Closed

What is the reason for C-RW-VALUE? #174

tbu- opened this issue Jul 3, 2018 · 4 comments

Comments

@tbu-
Copy link
Author

tbu- commented Jul 3, 2018

I see a reason against it, for every such function down the call stack, you'll add one reference to the reader/writer object. This is inefficient if the compiler doesn't notice that and can rewrite function signatures (which is only the case if it knows all call sites).

E.g. just having two levels of such functions results in &mut &mut &mut File, because each of the functions, including the one calling read or write needs to add another reference layer, it cannot pass the object by-value if it needs to call another method on that object. File is just a 32-bit integer on Linux, hiding it behind three references makes it slower.

@dtolnay
Copy link
Member

dtolnay commented Jul 3, 2018

Performance was not a motivation for the guideline. It is chiefly about clarity and simplicity.

Compare the amount of noise in these signatures:

use std::io::Write;

fn write_by_value<W: Write>(_w: W) {}

fn write_by_mut_ref<W: ?Sized + Write>(_w: &mut W) {}

Counting everything but the function names, the second one is 60% more characters and all of that is noise. It's not even more usable -- the noise amounts to making the function usable with strictly fewer types.

Compare also the call site:

let mut buffer = [0u8; 256];

write_by_value(&mut buffer[..]);

// oh my god
write_by_mut_ref(&mut &mut buffer[..]);

The mut ref one is hard to use because Write implementations are built around the expectation that the implementor is passed by value.

By value is also more suitable for writer adapters:

write_by_value(Adapter::new(&mut underlying));

// :(
write_by_mut_ref(&mut Adapter::new(&mut underlying));

@tbu-
Copy link
Author

tbu- commented Jul 6, 2018

Hm. Can we point out the disadvantages in this approach in the docs?

@KodrAus
Copy link
Contributor

KodrAus commented Dec 21, 2020

Performance caveats are a bit of a cross-cutting concern for API design that probably impact a number of guidelines, not just this one.

I'll go ahead and close this one, but but I think there's room for another resource on performance-sympathetic tactics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants