java - 要求重写反射,因为它很慢 - 事实并非如此?

标签 java reflection

我得到了一个包含 200 个字段的文件,其值是使用反射检索的。我被要求重写它,因为它很慢。该文件有 200 个字符串字段,检索方式如下:

for (Field f : this.getClass().getFields())
        {
            try
            {
                Object o = f.get(this);
            }
        }

我已将代码推断为三个类进行测试;一种使用“完全”反射、部分反射和不反射的方法。

“完全”反射是上面列出的示例。它获取字段,循环遍历它们,然后获取与该字段关联的对象:

//Two hundred strings declared = "test String"

public void reflection()
            throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {

        int count = 0;
        long timer = System.nanoTime();
        for (Field f : this.getClass().getFields()) {
            count++;
            Object o = f.get(this);
        }

        System.out.println(count);
        System.out.print("Reflection: ");
        System.out.println(System.nanoTime() - timer);

    }

更少的反射涉及将所有字段的名称放入数组中并简单地执行 get() 方法:

//Two hundreds Strings declared = "test string"
//array holding the names of all the strings
public void reflection()
        throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {

    int count = 0;
    long timer = System.nanoTime();

    for (String s : fieldnames) {
        Field field = this.getClass().getField(s);
        Object obj = field.get(this);
        count++;
    }
    System.out.println(count);
    System.out.print("Less reflection: ");
    System.out.println(System.nanoTime() - timer);

}

最后一个完全没有反射。这200个字符串被写出来,然后在运行时分配给另一个字符串。

//Two hundred strings declared = "test String"
public void reflection()
            throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
    int count = 0;
    long timer = System.nanoTime();

    String newVariable1 = variable1;
    String newVariable2 = variable2;
    //continued for all two hundred

    System.out.print("No reflection: ");
    System.out.println(System.nanoTime() - timer);
}

当我运行“完整”反射时,我得到: 反射(reflection):1511155

当我运行较少的反射时,我得到: 较少反射:1811682

当我不运行反射时,我得到: 无反射:199956

虽然这些数字有所不同,但趋势是相同的:我的结果与我的预期完全相反!使用的反射越少,速度就越慢?我使用 System.nanoTime() 是否错误?我对反射(reflection)有误解吗?编译器又跟我开了个玩笑吗?

最佳答案

Have I been misinformed about reflection?

没有。

常规 Java 比反射 Java 更快。 (我的内存1是性能差异不像旧版本的 Java 中那么大,但仍然存在显着差异。)

Is the compiler playing another joke on me?

没有。

这里实际上是一个写得不好的“微基准”示例,它会给您带来误导性的结果。

请阅读此问答 - How do I write a correct micro-benchmark in Java?

<小时/>

1 - 如果有人可以找到可靠的引用资料来支持这一点,请告诉我。

关于java - 要求重写反射,因为它很慢 - 事实并非如此?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39854739/

相关文章:

java - 如何在循环链表中找到最大子序列和

c# - 使用 CustomAttributes 与 GetCustomAttributes() 的优势

java - 将消息与目标类实例创建关联的最佳实践

c++ - typedef vector

java - 意外的多线程结果和计时

java - Mockito 具有静态类和返回 void 的方法

java - 我的 SQL 使用 java 程序插入值

斯卡拉 2.10 : Dynamically instantiating case classes

c# - 迭代变量和查找特定类型实例的技术

java - Kotlin:像在 Java 中一样创建一个常规数组