【发布时间】:2013-02-20 00:23:18
【问题描述】:
我要问的是这样做是否有区别:
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,因为它对我来说似乎更自然。
那么第一种和第二种方式之间是否存在风格/约定/性能差异?
谢谢,
正如我测试的 cmets 中所建议的,在我的基准测试中,动态方法更快。
这是测试代码:
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 毫秒。
但这对我来说是不确定的,因为我不知道编译器决定优化什么以及何时决定。
这就是我想要找出的。
【问题讨论】:
-
你试过了吗?是不是更快?
-
我会说速度差异(无论是什么)都不值得权衡哪个更具可读性。
-
这与性能无关,但如果你想对代码进行单元测试,使用静态方法是个坏主意stackoverflow.com/questions/11591564/…
-
@david99world 哪个更易读?
-
我想说情况并非如此,因为
private方法本质上也是final,因此与static方法一样可以静态调用和内联。
标签: java performance coding-style static-methods