Earlier quoted context omitted.
Rust doesn't have to output more code than a C compiler. But it tends to because most rust programs are stuffed full of bounds checks. And bounds checks aren't small. As well as the conditional itself, every bounds check also includes: - A custom panic message (so you know which line of code crashed) - Some monomorphized formatting code to output that message - The infrastructure to generate a stack trace after a pan…
I'd appreciate any more tips or resources you might have about reducing Rust code bloat. I want my library [1] to be acceptable to the most strident anti-bloat curmudgeons, so they'll make their UIs accessible. [1]: https://github.com/AccessKit/accesskit
The things I reach for in practice are godbolt and cargo asm[1] - which can show me the actual generated assembler for functions in my codebase. And twiggy[2], which can tell you which functions are the biggest in your compiled binary and point out where monomorphization is expensive.
When I’m developing, I regularly run a script which compiles my code to wasm and tells me how the wasm file size has changed since the last time I compiled it.
Some tips:
Try to avoid array lookups with an index when you can. When looping, use slice iterators and when making custom iterators, wrap the slice iterator rather than storing a usize index yourself.
Be careful of monomorphization. If you’re optimising for size, it can be better to take a dyn Trait rather than making a function generic.
And play around with your wasm API surface area. It takes a lot more code to pass complex objects & strings back and forth to javascript than other types.
But otherwise, good luck! Love the project.