Java:死码消除(Java: Dead code elimination)
我想知道Java如何处理以下情况:
假设我有一个名为Debug的类,如下所示:
public class Debug { private static final boolean isAssertEnabled = true; public static void assertTrue(boolean b, String errorMessage) { if (isAssertEnabled) { if (!b) { throw new RuntimeException(errorMessage); } } } }
并假设我的代码有一个如下所示的调用:
... Debug.assertTrue((x + y != z) && (v - u > w), "Some error message"); ....
我有几个问题:
- 如果isAssertEnabled标志设置为false ,那么对Debug.assertTrue的整个调用是否会被编译出来? 请注意,检查isAssertEnabled == true是否仅在函数调用后进行。
- 如果整个调用都被编译出来,那么这是否意味着对布尔表达式的求值被编译出来? 如果没有任何评价,那将是一种浪费。
感谢您的帮助!
I'd like to know how Java would handle the following scenario:
Suppose I have a class called Debug, which looks like this:
public class Debug { private static final boolean isAssertEnabled = true; public static void assertTrue(boolean b, String errorMessage) { if (isAssertEnabled) { if (!b) { throw new RuntimeException(errorMessage); } } } }
and suppose my code has a call that looks something like this:
... Debug.assertTrue((x + y != z) && (v - u > w), "Some error message"); ....
I have a few questions:
- If the isAssertEnabled flag is set to false, will the whole call to Debug.assertTrue be compiled out? Please note that the check if isAssertEnabled == true is only made inside the function after it was called.
- If the whole call does get compiled out, does that also mean that the evaluation of the boolean expression is compiled out? Would be a waste to evaluate that expression for nothing.
Thanks for you help!
原文:https://stackoverflow.com/questions/4756462
更新时间:2023-10-02 13:10