Java通用接口性能 [英] Java generic Interface performance

查看:75
本文介绍了Java通用接口性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的问题,但我想答案很棘手.

Simple question, but tricky answer I guess.

使用通用接口会损害性能吗?

Does using Generic Interfaces hurts performance?

示例:

public interface Stuff<T> {

    void hello(T var);
}

vs

public interface Stuff {

    void hello(Integer var);  <---- Integer used just as an example
}

我首先想到的不是.泛型只是语言的一部分,编译器会对其进行优化,就好像没有泛型一样(至少在这种特殊情况下,泛型接口).

My first thought is that it doesn't. Generics are just part of the language and the compiler will optimize it as though there were no generics (at least in this particular case of generic interfaces).

这正确吗?

推荐答案

由于编译器有时会添加合成桥方法,因此可能会造成轻微的性能损失.考虑以下示例:

There is potential for a minor performance loss, because the compiler sometimes adds synthetic bridge methods. Consider the following example:

public class GenericPerformance {
    public static void main(final String[] args) {
        final Stuff<Integer> stuff = new IntStuff();
        final Integer data = stuff.getData();
        stuff.putData(data);
    }
}

interface Stuff<T> {
    T getData();
    void putData(T stuff);
}

class IntStuff implements Stuff<Integer> {
    private Integer stuff;
    public Integer getData() {
        return stuff;
    }
    public void putData(final Integer stuff) {
        this.stuff = stuff;
    }
}

如果查看生成的字节码,您将看到:在主要方法中,已擦除的接口方法

If you look at the generated bytecode, you will see: In the main method, the erased interface methods

java.lang.Object Stuff.getData()
void Stuff.putData(java.lang.Object)

被调用.该方法在带有签名的 IntStuff 中实现

are invoked. That methods, implemented in IntStuff with the signatures

java.lang.Object getData()
void putData(java.lang.Object)

两者都带有修饰符 public bridge Composite ,都委托给真实"方法

both with the modifiers public bridge synthetic, delegate to the "real" methods

java.lang.Integer IntStuff.getData()
void putData(java.lang.Integer)

第一个合成方法仅返回Integer结果,而第二个合成方法则在调用 putData(Integer)之前执行从Object到Integer的转换.

The first synthetic method merely returns the Integer result, while the second performs a cast from Object to Integer before calling putData(Integer).

如果将 stuff 变量更改为键入 IntStuff ,则将调用两个 Integer 方法,而不是合成的 Object 方法.

If you change the stuff variable to type IntStuff, then both Integer methods are called instead of the synthetic Object methods.

这篇关于Java通用接口性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆