gpt4 book ai didi

java方法调用有多贵

转载 作者:IT老高 更新时间:2023-10-28 11:49:42 26 4
gpt4 key购买 nike

我是一个初学者,我一直认为重复代码是不好的。但是,似乎为了不这样做,您通常必须进行额外的方法调用。假设我有以下类(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?

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

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?

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

What's the best programming practice?

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

关于java方法调用有多贵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6495030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com