我所问的是这样做是否有区别:
这个:
这是服务代码:
100000次迭代中,动态方法用时577毫秒,静态方法用时615毫秒。然而,对我来说这并不具有决定性意义,因为我不知道编译器何时以及如何进行优化。这正是我试图找出的。
public Something importantBlMethod(SomethingElse arg) {
if (convenienceCheckMethod(arg)) {
// do important BL stuff
}
}
private boolean convenienceCheckMethod(SomethingElse arg) {
// validate something
}
这个:
public Something importantBlMethod(SomethingElse arg) {
if (convenienceCheckMethod(arg)) {
// do important BL stuff
}
}
private static boolean convenienceCheckMethod(SomethingElse arg) {
// validate something
}
我实际上使用选项1,因为对我来说似乎更自然。
那么第一种方法和第二种方法之间是否存在样式/惯例/性能差异?
谢谢,
如评论中所建议的,我进行了测试,在我的基准测试中,动态方法更快。
这是测试代码:
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次迭代中,动态方法用时577毫秒,静态方法用时615毫秒。然而,对我来说这并不具有决定性意义,因为我不知道编译器何时以及如何进行优化。这正是我试图找出的。
private
方法本质上也是final
的,因此和static
方法一样可以被静态调用和内联化。 - Theodoros Chatzigiannakis