使用静态私有方法真的比实例私有方法更快/更好吗? [英] Is using static private methods really faster/better than instance private methods?
问题描述
我要问的是在做这个之间是否有区别:
What I'm asking is whether there is a difference between doing this:
public Something importantBlMethod(SomethingElse arg) {
if (convenienceCheckMethod(arg)) {
// do important BL stuff
}
}
private boolean convenienceCheckMethod(SomethingElse arg) {
// validate something
}
b
public Something importantBlMethod(SomethingElse arg) {
if (convenienceCheckMethod(arg)) {
// do important BL stuff
}
}
private static boolean convenienceCheckMethod(SomethingElse arg) {
// validate something
}
我实际上使用选项1,因为它对我来说更自然。
I actually use option 1 as it seems more natural to me.
第一种和第二种方式之间的惯例/性能差异?
So is there a style/convention/performance difference between the first and the second way ?
谢谢,
如我在测试它的评论中所建议的,在我的基准测试中,动态方法更快。
As suggested in the comments I tested it, in my benchmarks the dynamic method is faster.
这是测试代码:
public class Tests {
private final static int ITERATIONS = 100000;
public static void main(String[] args) {
final long start = new Date().getTime();
final Service service = new Service();
for (int i = 0; i < ITERATIONS; i++) {
service.doImportantBlStuff(new SomeDto());
}
final long end = new Date().getTime();
System.out.println("diff: " + (end - start) + " millis");
}
}
这是服务代码:
public class Service {
public void doImportantBlStuff(SomeDto dto) {
if (checkStuffStatic(dto)) {
}
// if (checkStuff(dto)) {
// }
}
private boolean checkStuff(SomeDto dto) {
System.out.println("dynamic");
return true;
}
private static boolean checkStuffStatic(SomeDto dto) {
System.out.println("static");
return true;
}
}
对于100000次迭代,动态方法传递577ms,静态615ms。
For 100000 iterations the dynamic method passes for 577ms, the static 615ms.
但是对我来说这是不确定的,因为我不知道什么,什么时候编译器决定优化。
This however is inconclusive for me since I don't know what and when the compiler decides to optimize.
这是我想要找出的。
推荐答案
性能明显:可忽略。
经验法则是声明你的方法static,如果它不与它的类的任何成员交互。
The rule of thumb is to declare your method static if it doesn't interact with any members of its class.
这篇关于使用静态私有方法真的比实例私有方法更快/更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!