Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
scala 是如何处理matching 的?它只是在字节码级别转换为编译器分支的语法糖,还是隐藏在幕后的一些巧妙技巧?
match
将整数值(例如,Int、Char)与常量匹配通常被转换为 TableSwitch(通过索引数组的 O(1) 查找时间)或 LookUpSwitch(通过二进制搜索的 O(log n) 查找时间)字节码指令。如果您将变量模式或通配符模式作为包罗万象的分支,情况也会如此。
您可以使用 @switch 注释来确保这确实发生。
对于非整数值,可用的优化更有限;但是,据我了解编译器代码,编译器至少会检查公共子条件(它记得)和共享前缀。