4 ms·
One thing I've been curious about -- but not enough to actually run through the disassembly yet -- is the performance of Rust matching on enums vs C/C++ switch
by cmrdporcupine 4y ago
One thing I've been curious about -- but not enough to actually run through the disassembly yet -- is the performance of Rust matching on enums vs C/C++ switch statement -- in particular in e.g. a 'bytecode' interpreter loop.
C compilers do a pretty good job of optimizing these into something pretty efficient, and I imagine it helps that the size of the case values is constant, and it can be turned by the compiler into either a jump table lookup or an unrolled jmp depending on size, etc.
Rust enums, in contrast, can be variable sized at match time. And the elements can be nested a few levels deep. The obvious way to write an opcode execution loop in Rust -- a pattern match over an enum of opcodes -- I'm curious if this can be made to perform as well as in C/C++.
(I've been writing a virtual machine interpreter loop and so have a modest interest in seeing how this kind of thing, though I'm not optimizing for performance yet, so)
Don't see any explicit mention of this in this document.
- __s 4y ago1. C compilers don't do a good job, & thus even CPython, which has historically stuck to rather vanilla C, uses computed goto, as described in https://eli.thegreenplace.net/2012/07/12/computed-goto-for-efficient-dispatch-tables https://eli.thegreenplace.net/2012/07/12/computed-goto-for-e... I resorted to similar techniques in optimizing Befunge: https://github.com/serprex/Befunge https://github.com/serprex/Befunge (See bejit.c & marsh.c/marsh.h) 2. Rust enums are not variable sized, think of them as tagged C unions, where the Rust compiler can sometimes apply tricks, for example making Option<Vec<T>> the same size as Vec<T> 3. match can specialize for straight forward cases, when in doubt use https://godbolt.org https://godbolt.org
- cmrdporcupine 4y agoNeat (re: godbolt). But the output is super bloated for Rust -- even with no_std and the panic handler stubbed out. https://godbolt.org/z/nW79G1o71 https://godbolt.org/z/nW79G1o71 Also my old 6502 then 68000 brain never learned to read x86 assembly. :-) I find ARM/Aarch64 easier to grock. I might do this same test on the M1 Mac I have handy here, but fiddle with compiler until I can get an absolutely tiny binary and then compare to C. Some day.
- kibwen 4y agoYour link there is compiling in debug mode, using opt-level=0 (the default), which is why it produces 1800 lines of output. If you do opt-level=3 (which corresponds to `cargo build --release`), it becomes 300 lines of output: https://godbolt.org/z/aYKMne5Wq https://godbolt.org/z/aYKMne5Wq