Sim*_*eon 2 java performance static-methods coding-style
我要问的是这样做是否有区别:
public Something importantBlMethod(SomethingElse arg) {
if (convenienceCheckMethod(arg)) {
// do important BL stuff
}
}
private boolean convenienceCheckMethod(SomethingElse arg) {
// validate something
}
Run Code Online (Sandbox Code Playgroud)
还有这个:
public Something importantBlMethod(SomethingElse arg) {
if (convenienceCheckMethod(arg)) {
// do important BL stuff
}
}
private static boolean convenienceCheckMethod(SomethingElse arg) {
// validate something
}
Run Code Online (Sandbox Code Playgroud)
我实际上使用选项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");
}
}
Run Code Online (Sandbox Code Playgroud)
这是服务代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
对于100000次迭代,动态方法通过577ms,静态615ms.
然而,这对我来说是不确定的,因为我不知道编译器何时以及何时决定优化.
这就是我想要找到的.
归档时间: |
|
查看次数: |
1530 次 |
最近记录: |