我想知道JVM/javac是否足够聪明
// This line...
string a = foo();
string foo()
{
return bar();
}
string bar()
{
return some-complicated-string computation;
}
Run Code Online (Sandbox Code Playgroud)
成
string a = bar();
Run Code Online (Sandbox Code Playgroud)
或者在发布案例中删除对foo()的不必要调用(因为无法访问的代码):
string a = foo(bar());
// bar is the same
...
string foo(string b)
{
if (debug) do-something-with(b);
}
Run Code Online (Sandbox Code Playgroud)
对于第一个例子我的感觉是肯定的,对于第二个例子我的感觉是"不太确定",但是有人可以给我一些指示/链接来确认吗?
我已经写了近一年的Java了,我已经看到了两种不同的约定,用于人们如何实现他们的setter.
为了说明这一点,以下是两种惯例的示例.(我也很想知道这两个模式的简洁名称)
使用第一个约定的类,不返回其"set"方法.像这样:
public class Classic{
private double _x;
private double _y;
public Classic(){
x = 0;
y = 0;
}
public void setX(double d){//or boolean with a type check on input
x = d;
}
public void sety(double d){
y = d;
}
}
Run Code Online (Sandbox Code Playgroud)
使用替代约定的类从其setter方法返回.像这样:
public class Alternative{
private double _x;
private double _y;
public Alternative(){
x = 0;
y = 0;
}
public Alternative setX(double d){
x = d;
return(this);
}
public Alternative sety(double d){
y = d; …Run Code Online (Sandbox Code Playgroud) 我做了一些研究,但我主要看到c ++的答案.我最接近的就是这个.我也看过这个页面,但它并没有真正解释任何事情.
如果我使用第二段代码有什么好处吗?会有明显的性能差异吗?记忆呢?如果重复完成怎么办?
现在我有这个功能.我确信这样做的好处是代码可读性:
private static Bitmap resize(Bitmap image, int maxWidth) {
float widthReducePercentage = ((float) maxWidth / image.getWidth());
int scaledHeight = Math.round(image.getHeight() * widthReducePercentage);
return Bitmap.createScaledBitmap(image, maxWidth, scaledHeight, true);
}
Run Code Online (Sandbox Code Playgroud)
现在,我有第二段代码:
private static Bitmap resize(Bitmap image, int maxWidth) {
return Bitmap.createScaledBitmap(image, maxWidth, Math.round(image.getHeight() * (float) maxWidth / image.getWidth()), true);
}
Run Code Online (Sandbox Code Playgroud)
一个更简单的例子是:
for(;;) {
String foo = "hello";
Console.print(foo + "world");
}
Run Code Online (Sandbox Code Playgroud)
与
for(;;) {
Console.print("hello" + "world");
}
Run Code Online (Sandbox Code Playgroud) Java是否像其他语言一样指令在编译时或JIT时内联方法?
我们有很多只调用super方法的方法.这清楚地表明它不会忘记覆盖该方法.
例如,您已经覆盖了equals方法,但是使用了与超级实现相同的哈希码.这使得后来的开发人员明白了hashcode方法并没有忘记实现.这对于setter和getter或者添加和删除也是有效的.
但是编译器应该内联这个方法.
可能重复:
java中是否有内联函数?
我来自C++,我会写
for (int i = 0; i < numNonZero(); ++i)
Run Code Online (Sandbox Code Playgroud)
知道numNonZero(),非常小,"内联"只会从编译后的代码中消失.在Java中怎么样?我应该在我的班级中有一个int _numNonZero并写
for (int i = 0; i < _numNonZero; ++i)
Run Code Online (Sandbox Code Playgroud)
为了最大速度?
java ×5
inline ×3
android ×1
coding-style ×1
javac ×1
jvm ×1
optimization ×1
performance ×1
setter ×1