3 ms·
What does that explain? Let's say you did add(add("foo", "bar"), "baz"). The inner add would return a String, and then all subsequent adds would have the exac
by Dylan16807 5y ago
What does that explain?
Let's say you did add(add("foo", "bar"), "baz").
The inner add would return a String, and then all subsequent adds would have the exact same optimization you're quoting.
There is no downside, performance-wise.
- masklinn 5y agoThat can not typecheck in Rust, unless you use something really odd like `Into<Cow<‘a, A>> where A: Add<B>` as your input types. And in languages where it does, you need either ubiquitously mutable strings (which everyone’s moved from because it generally screws you up) or refcounting.
- Dylan16807 5y ago> That can not typecheck in Rust, unless you use something really odd like `Into<Cow<‘a, A>> where A: Add<B>` as your input types. I'm not entirely sure what that means, but here I'll just go implement a version: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=140aa13a0ece32a5a333bcea42d07b69 https://play.rust-lang.org/?version=stable&mode=debug&editio... I think this is right. I haven't written Rust before. I copied Add to RAdd because you can't implement traits you don't own on types you don't own. And I didn't bother implementing it for numbers. There's a trait implementation that takes String and &str (directly copied from Add), and there's a version that takes &str and &str. Both of them return String. The generic function is just as generic as it always was, but of course you can't do this with actual Add without changing the standard library. You'd have to make the function less generic instead. > And in languages where it does, you need either ubiquitously mutable strings (which everyone’s moved from because it generally screws you up) or refcounting. It's the same String as ever. Owned and mutated by adding.
- gpderetta 5y agoBut mutable string are not an issue when not shared, which can be checked statically in rust, right?
- eklavya 5y agoNo, they won't in standard implementations we are not exactly allocating, the allocated buffer doubles each time, so it's amortised and not O(n^2). There is a downside for non trivial example code.
- Dylan16807 5y agoEvery add except the first one is using the same code in either version. The suggested change does not affect String + &str at all.
- eklavya 5y agoOk, maybe I misunderstood, I thought you were saying &str + &str with precomputed capacity in call cases, let me read it again.