Date: Sat, 24 May 2025 10:58:55 +0200
There are no performance advantages.
If/else statements can be optimized the same way as switch.
Why should they fundamentally be non-optimizable? They can be easily converted to and from switch internally by the compiler or lead to the same intermediate representation, if all they do is compare one variable with a string.
Jump tables also have a pipeline penalty. Why do you think they would suffer less from it? Both jump targets (from a conditional jump or an indexed table) are deterministic, and both are decided dynamically at runtime on some input value. If the jump target is calculated wrongly, the pipeline is emptied. You would need code without jumps, which is possible in many cases and often employed by compilers. Also CPUs (with the help of compilers) are quite good at predicting jumps.
Are switch statements better maintainable than equivalent code? Depends on the use case. But that is why powerful pattern matching is introduced to allow this coding style more often and in a more powerful way -
- with added usability improvements like disallowing fall-through and wild jumps (compared to switch).
If those switch (anti)-features are needed, it is for a special case and surely won't be the prevailing paradigm, as is proven with switch (integer) and common coding guidelines disallowing fall-through, demanding always present 'default', demanding all possible values are listed or disallowing goto. I agree any of those forbidden features can be useful sometimes, but rather in special rare circumstances.
-----Ursprüngliche Nachricht-----
Von:Zhao YunShan via Std-Proposals <std-proposals_at_[hidden]>
Gesendet:Sa 24.05.2025 10:26
Betreff:Re: [std-proposals] A draft for modern switch
An:std-proposals_at_[hidden];
CC:Zhao YunShan <dou1984_at_[hidden]>;
The "multiway branch" construct demonstrates excellent performance characteristics and serves as the optimal solution in this scenario. Traditional if...else if chains appear fundamentally non-optimizable in this manner. It remains to be determined whether pattern matching can facilitate equivalent low-level optimizations.
Regarding string-based switch statements, empirical evidence suggests they can similarly benefit from multiway branch optimization. If this holds true, significant portions of existing codebase containing if...else if... chains could be refactored using switch statements. Furthermore, even routing/dispatch tables might be replaceable with switch constructs - with the added advantage that switch statements avoid CPU pipeline prediction penalties through deterministic jump table implementations.
From an architectural perspective, switch statements may emerge as a prevailing paradigm in future system design, given their combination of performance advantages and maintainability benefits.
--
Std-Proposals mailing list
Std-Proposals_at_[hidden]
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
Received on 2025-05-24 09:06:32