25ms 是创建 ByteBuddy 子类的典型时间吗?

Is 25ms a typical time for creating a ByteBuddy subclass?

在创建代理时,我看到的最佳时间约为 25 毫秒(3.2Ghz 处理器)。我正在尝试 trim 从代码执行中减少数十毫秒,所以想知道这是典型现象还是我做错了什么?

我正在尝试使用 ByteBuddy 代理 Hibernate 实体,设置如下:

休眠实体:

@Entity
@Table(name = "device")
public class Device implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private long id;
    @Version
    @Column(name = "version", nullable = false)
    private int version;
    // ... about 20 more annotated fields representing columns

代理创建:

private static ByteBuddy byteBuddy = new ByteBuddy();

// ...

private Device getProxy(long id) {
    Device target = new Device();
    // ... populates the target with necessary information

    Device proxyDevice = byteBuddy
        .subclass(Device.class)
        .method(any()).intercept(to(new CatchAllInteceptor()))               
        .method(isGetter()
            .or(isHashCode())
            .or(isToString())
            .or(isEquals()))
            .intercept(to(target))
        .make() 
        .load(this.getClass().getClassLoader())
        .getLoaded()
        .newInstance();

我是 ByteBuddy 的新手,因此很可能存在明显的错误 - 例如为了加快每次调用的目的而重用上述某些定义的能力。此代码块每秒被调用 1200 次,所以我希望 trim 尽可能多。

我无法按 the docs comparison table (885.983 - 5'408.329 ns) 符合我的经验 - 尽管我注意到这些被引用为基线 Object 子类计时。

class 加载程序创建可能是您的测量中成本最高的部分。在 Hibernate 中,classes 实际上被注入到目标 class 加载器中,从而降低了一些成本。这也在基准测试中完成,因为它是 cglib 和 Javassist 进行适当比较的默认方法。

您可以通过将 ClassLoadingStrategy.Default.INJECTION 指定为 load 方法的第二个参数来使用注入策略。