问题描述
我正在尝试比较这两种实现枚举值的方法(有或没有反射).
I'm trying to compare this two ways to achieving the enums values (with and without reflection).
这是我的测试班:
public class ReflectionOnEnumsTests2 {
enum TestEnum { ONE, TWO, THREE; }
public static void main(String[] args) {
long n = 600_000_000;
int stub;
//test without Reflection
long timeStartWithoutReflection = System.currentTimeMillis();
for (int i = 0; i < n; i++){
TestEnum[] values = TestEnum.values();
stub = values.length;
}
System.out.println("Time consuming with reflection: " + (System.currentTimeMillis() - timeStartWithoutReflection));
//test Reflection
long timeStartWithReflection = System.currentTimeMillis();
for (int i = 0; i < n; i++){
TestEnum[] values = TestEnum.class.getEnumConstants();
stub = values.length;
}
System.out.println("Time consuming with reflection: " + (System.currentTimeMillis() - timeStartWithReflection));
}
}
我对测试结果感到困惑.大约花费了相同的时间.我希望class.getEnumConstants会比values()方法慢得多.
And I'm confused about the test results. There is approximately the same time consuming. I expected that class.getEnumConstants would be much slower than values() method.
结果:
费时的反思:6050
费时的反思:7483
Results:
Time consuming with reflection: 6050
Time consuming with reflection: 7483
JDK版本:1.8.0_60
问题:
那为什么性能没有差异?
Question:
So why there is no difference in performance?
推荐答案
您自己的测试表明,非反射方法的速度提高了约20%.这可能不像您预期的那么多,但这是不小的差异.
Your own tests show the non-reflective approach being around 20% faster. That may not be as much as you expected, but it's a non-trivial difference.
但是,实际上,很难以任何方式概括您的结果.性能测试Java非常棘手.尤其是JIT编译会导致综合基准测试(例如您的基准测试)产生仅代表自身的结果,并且不能准确地表征在实际应用程序上下文中可以预期的性能.
In fact, though, it's difficult to generalize your results in any way. Performance-testing Java is tricky. JIT compilation in particular can cause synthetic benchmarks such as yours to produce results that represent only themselves, and do not accurately characterize performance that can be expected in real application contexts.
无论如何,您都提出了错误的标准来比较这两种方法.您应该在任何可能的地方使用普通的非反射方法,因为它提供了更好的API ,即使性能差异只是中等.曾经使用反射的唯一原因是,直到运行时您才能知道足够多的信息来确定要采取的措施的详细信息.这种情况很少见.
In any event, you are proposing the wrong criterion for comparing these two approaches. You should use the ordinary, non-reflective approach wherever you can because it provides a better API, even if the performance difference is only moderate. The only reason ever to use reflection is that you cannot know enough until run time to determine the details of the action to take. Such circumstances are rare.
这篇关于枚举values()方法和class.getEnumConstants()的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!