TL; Dr,滚动到最后的编辑。我将这一切都留在这里,让人们可以从这个讨论的演变中读到。如果在编译/反编译后返回null if {return}
我已经得到了一个库下面的代码:
private void addData(JSONObject jsonObject) {
if (jsonObject == null){
return;
}
if (jsonObject.has("elements")){
try {
addData(jsonObject.getJSONArray("elements"));
} catch (JSONException e) {
e.printStackTrace();
}
}else{
try {
getArray().put(jsonObject);
} catch (JSONException e) {
}
}
}
现在Android Studio中,我使用这个库。当我进入它(通过按Ctrl + B去的函数的定义),我看到它,它反编译这样:
private void addData(JSONObject jsonObject) {
if(jsonObject != null) {
if(jsonObject.has("elements")) {
try {
this.addData(jsonObject.getJSONArray("elements"));
} catch (JSONException var3) {
var3.printStackTrace();
}
} else {
try {
this.getArray().put(jsonObject);
} catch (JSONException var4) {
;
}
}
}
}
我知道这有效它是相同的,但在我心中这会影响性能。我的代码会更快,如果jsonObject
经常为空,(因为它不必跳到功能的末尾,然后跳出来,如第二个版本所做的那样),如果jsonObject
是第二个版本,效率更高更经常地不是null
。
我对改变性能的声明是否正确?Java是如何编译它的呢?
编辑:
好了,因为我看到一些答复,指出这是完全一样的,让我再详细一点。我有过C和C++的多门课程。这些语言会立即被翻译成程序集,从而很容易看到所有的跳转。
说,我们已经得到这个伪代码:如果事情是假的
function a(){
//p1
b(); //jump to b()
//p2
}
function b(){
if (something){//if not, jump to. If, don't jump } (1st jump)
goto whereyoucamefrom;//whereyoucamefrom in this case is b(); in function a(), so it'll jump to p2 (1st jump)
}
goto whereyoucamefrom;//whereyoucamefrom is now also b();, so going to p2 again. (2nd jump, only when not something.)
}
这导致1周跳,如果事情是真实的,2:
function a(){
//p 1
b();
//p2
}
function b(){
if (something){
return;
}
}
这将被编译成。这绝对看起来比我更有效:
function b(){
if (!something){//if not, jump to else (1st jump)
//body of function
goto afterelse;
}else{//if the body got executed, jump to } (1st jump)
goto endoffunction;
}
goto whereyoucamefrom;//this is endoffunction (2nd jump, always gets executed)
}
这总是会导致2跳。
编辑: 好吧,我将尝试使用此编辑来澄清(再一次)我的意图与这篇文章。
我的问题是有关跳转(或跳转)级别的优化。我的问题是,是不是真的
function a(){
if (something){
jump out of function;
}
//body
jump out of function;
}
比
function a(){
if (something){
jump over else
}else{
//body
}
jump out of function
}
更快?如果是这样,为什么java编译器不能正确执行此操作?请参阅原始帖子,了解我编写的代码和decompiled
版本的编译版本。
似乎是一个很好的问题,谁下降了谁? – droidev
性能应该是一样的。你必须检查'jsonObject'至少一次以确定它是否为'null'。反编译的代码在我的oppinion中稍微好一点,因为它只将方法留在一个分支上(不需要'return;'需要)。 – Turing85
@ Turing85我知道你必须检查是否为null,但我也在考虑跳转到这里。当处理器执行时,跳转(或跳转)在处理器上非常昂贵,因为它必须冲洗管道,至少需要3次,最多可达20个时钟周期。 –