本文介绍了方法提取会对代码性能产生负面影响吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您的方法很长,大约有 200 行对时间非常敏感的代码.是否有可能将部分代码提取到单独的方法中会减慢执行速度?

Assume you have quite long method with around 200 lines of very time sensitive code. Is it possible that extracting some parts of code to separate methods will slow down execution?

推荐答案

很可能,您会得到加速.问题是优化一个 200 行的野兽很难.实际上,当方法太长时,Hotspot 会放弃它.一旦我通过简单地拆分长方法实现了 2 的加速因子.

Most probably, you'll get a speedup. The problem is that optimizing a 200 lines beast is hard. Actually, Hotspot gives it up when the method is too long. Once I achieved a speedup factor of 2 by simply splitting a long method.

短方法很好,它们会根据需要被内联.因此方法调用开销被最小化.通过内联,Hotspot 可能会重新创建您的原始方法(由于长度过长而不太可能)或创建多个方法,其中一些方法可能包含原始方法中不存在的代码.

Short methods are fine, and they'll be inlined as needed. So the method call overhead gets minimized. By inlining, Hotspot may re-create your original method (improbable due to its excessive length) or create multiple methods, where some of them may contain code not present in the original method.

答案是是的,它可能会变慢."问题是所选择的内联可能不是最理想的.但是,这是非常不可能的,我希望能够加快速度.

The answer is "yes, it may get slower." The problem is that the chosen inlining may be suboptimal. However, it's very improbable, and I'd expect a speedup instead.

这篇关于方法提取会对代码性能产生负面影响吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:15