java方法调用有多贵 [英] java how expensive is a method call

查看:118
本文介绍了java方法调用有多贵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者,我一直都认为重复代码是不好的。但是,似乎为了不这样做,通常需要额外的方法调用。假设我有以下类

I'm a beginner and I've always read that it's bad to repeat code. However, it seems that in order to not do so, you would have to have extra method calls usually. Let's say I have the following class

public class BinarySearchTree<E extends Comparable<E>>{
    private BinaryTree<E> root;
    private final BinaryTree<E> EMPTY = new BinaryTree<E>();
    private int count;
    private Comparator<E> ordering;

    public BinarySearchTree(Comparator<E> order){
        ordering = order;
        clear();
    }

    public void clear(){
        root = EMPTY;
        count = 0;
    }
}

我是否更适合我复制和将我的clear()方法中的两行粘贴到构造函数中而不是调用实际的方法?如果是这样,它会产生多大的差异?如果我的构造函数进行了10次方法调用,每次调用只需将一个实例变量设置为值,该怎么办?什么是最好的编程实践?

Would it be more optimal for me to just copy and paste the two lines in my clear() method into the constructor instead of calling the actual method? If so how much of a difference does it make? What if my constructor made 10 method calls with each one simply setting an instance variable to a value? What's the best programming practice?

推荐答案


仅仅复制和粘贴对我来说是否更合适?我的clear()方法中的两行进入构造函数而不是调用实际方法?

Would it be more optimal for me to just copy and paste the two lines in my clear() method into the constructor instead of calling the actual method?

编译器可以执行该优化。 JVM也是如此。编译器编写者和JVM作者使用的术语是内联扩展。

The compiler can perform that optimization. And so can the JVM. The terminology used by compiler writer and JVM authors is "inline expansion".


如果是这样,它会产生多大的差异?

If so how much of a difference does it make?

测量它。通常,你会发现它没有任何区别。如果你认为这是一个性能热点,那你就是在寻找错误的地方;这就是你需要测量它的原因。

Measure it. Often, you'll find that it makes no difference. And if you believe that this is a performance hotspot, you're looking in the wrong place; that's why you'll need to measure it.


如果我的构造函数进行了10次方法调用,每次只调用一个实例变量,该怎么办?值?

What if my constructor made 10 method calls with each one simply setting an instance variable to a value?

同样,这取决于生成的字节码和Java虚拟机执行的任何运行时优化。如果编译器/ JVM可以内联方法调用,它将执行优化以避免在运行时创建新堆栈帧的开销。

Again, that depends on the generated bytecode and any runtime optimizations performed by the Java Virtual machine. If the compiler/JVM can inline the method calls, it will perform the optimization to avoid the overhead of creating new stack frames at runtime.


什么是最好的编程习惯?

What's the best programming practice?

避免过早优化。最佳做法是编写可读且设计良好的代码,然后针对应用程序中的性能热点进行优化。

Avoiding premature optimization. The best practice is to write readable and well-designed code, and then optimize for the performance hotspots in your application.

这篇关于java方法调用有多贵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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