java方法调用有多昂贵

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6495030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:23:34  来源:igfitidea点击:

java how expensive is a method call

javaperformancemethodscall

提问by jhlu87

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;
    }
}

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() 方法中的两行复制并粘贴到构造函数中而不是调用实际方法对我来说是否更理想?如果是这样,它有多大区别?如果我的构造函数进行了 10 次方法调用,每次调用都只是将一个实例变量设置为一个值会怎样?什么是最佳编程实践?

采纳答案by Vineet Reynolds

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?

将我的 clear() 方法中的两行复制并粘贴到构造函数中而不是调用实际方法对我来说是否更理想?

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

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

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.

测量它。通常,您会发现它没有任何区别。如果您认为这是一个性能热点,那么您找错了地方;这就是为什么你需要测量它。

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

如果我的构造函数进行了 10 次方法调用,每次调用都只是将一个实例变量设置为一个值会怎样?

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.

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

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.

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

回答by Marcelo

I would definitely leave it as is. What if you change the clear()logic? It would be impractical to find all the places where you copied the 2 lines of code.

我肯定会保持原样。如果你改变clear()逻辑呢?找到复制两行代码的所有位置是不切实际的。

回答by Arafangion

The best practice is to measure twice and cut once.

最佳做法是测量两次并切割一次。

Once you've wasted time optimization, you can never get it back again! (So measure it first and ask yourself if it's worth optimisation. How much actual time will you save?)

一旦你浪费了优化时间,你就再也找不回来了!(所以先衡量一下,问问自己是否值得优化。你会节省多少实际时间?)

In this case, the Java VM is probably already doing the optimization you are talking about.

在这种情况下,Java VM 可能已经在进行您所说的优化。

回答by Michael Berry

Generally speaking (and as a beginner this means always!) you should never make micro-optimisations like the one you're considering. Always favour readability of code over things like this.

一般来说(作为初学者,这意味着永远!)你永远不应该像你正在考虑的那样进行微观优化。总是喜欢代码的可读性而不是这样的事情。

Why? Because the compiler / hotspot will make these sorts of optimisations for you on the fly, and many, many more. If anything, when you try and make optimisations along these sorts of lines (though not in this case) you'll probably make things slower. Hotspot understands common programming idioms, if you try and do that optimisation yourself it probably won't understand what you're trying to do so it won't be able to optimise it.

为什么?因为编译器/热点会为您即时进行这些优化,还有很多很多。如果有的话,当您尝试按照这些方式进行优化时(尽管不是在这种情况下),您可能会使事情变慢。Hotspot 理解常见的编程习语,如果您尝试自己进行优化,它可能无法理解您要执行的操作,因此无法对其进行优化。

There's also a much greater maintenance cost. If you start repeating code then it's going to be much more effort to maintain, which will probably be a lot more hassle than you might think!

还有更高的维护成本。如果您开始重复代码,那么维护起来会更加费力,这可能比您想象的要麻烦得多!

As an aside, you may get to some points in your coding life where you do need to make low level optimisations - but if you hit those points, you'll definitely, definitely know when the time comes. And if you don't, you can always go back and optimise later if you need to.

顺便说一句,您可能会在编码生活中遇到一些需要进行低级优化的点 - 但如果您达到这些点,您肯定会知道什么时候到来。如果您不这样做,您可以随时返回并在需要时进行优化。

回答by Peaches491

The pattern that I follow, is whether or not this method in question would satisfy one of the following:

我遵循的模式是这种方法是否满足以下条件之一:

  • Would it be helpful to have this method available outside this class?
  • Would it be helpful to have this method available in other methods?
  • Would it be frustrating to rewrite this every time i needed it?
  • Could the versatility of the method be increased with the use of a few parameters?
  • 在这个类之外使用这个方法会有帮助吗?
  • 在其他方法中使用这种方法会有帮助吗?
  • 每次需要时都重写它会令人沮丧吗?
  • 是否可以通过使用一些参数来增加该方法的通用性?

If any of the above are true, it should be wrapped up in it's own method.

如果以上任何一个是真的,它应该包含在它自己的方法中。

回答by Fabian Barney

Keep the clear()method when it helps readability. Having unmaintainable code is more expensive.

保留clear()方法有助于提高可读性。拥有不可维护的代码更昂贵。

回答by Paul Sonier

Optimizing compilers usually do a pretty good job of removing the redundancy from these "extra" operations; in many instances, the difference between "optimized" code and code simply written the way you want, and run through an optimizing compiler is none; that is to say, the optimizing compiler usually does just as good a job as you'd do, and it does it without causing any degradation of the source code. In fact, many times, "hand-optimized" code ends up being LESS efficient, because the compiler considers many things when doing the optimization. Leave your code in a readable format, and don't worry about optimization until a later time.

优化编译器通常可以很好地从这些“额外”操作中去除冗余;在许多情况下,“优化”代码和简单地按照您想要的方式编写并通过优化编译器运行的代码之间的区别是没有的;也就是说,优化编译器的工作通常与您所做的一样好,并且不会导致源代码的任何降级。事实上,很多时候,“手动优化”的代码最终效率较低,因为编译器在进行优化时会考虑很多事情。让你的代码保持可读的格式,不要担心优化,直到以后的时间。

"Premature optimization is the root of all evil." - Donald Knuth

“过早优化是万恶之源。” - 唐纳德·克努斯

回答by Andreas Dolk

The costof a method call is the creation (and disposal) of a stack frame and some extra byte code expressions if you need to pass values to the method.

如果需要将值传递给方法,方法调用的成本是创建(和处置)堆栈帧和一些额外的字节码表达式。

回答by Buhake Sindi

I wouldn't worry about method call as much but the logic of the method. If it was critical systems, and the system needed to "be fast" then, I would look at optimising codes that takes long to execute.

我不会担心方法调用,而是方法的逻辑。如果它是关键系统,并且系统需要“快速”,那么我会考虑优化需要很长时间执行的代码。

回答by adamjmarkham

Given the memory of modern computers this is very inexpensive. Its always better to break your code up into methods so someone can quickly read whats going on. It will also help with narrowing down errors in the code if the error is restricted to a single method with a body of a few lines.

鉴于现代计算机的内存,这是非常便宜的。将您的代码分解成方法总是更好的,这样人们就可以快速阅读正在发生的事情。如果错误仅限于具有几行正文的单个方法,它还有助于缩小代码中的错误范围。