在两次调用一个函数以及将返回值存储在变量之间选择哪个? [英] which one to choose between calling a function twice and storing the return value in a variable?

查看:93
本文介绍了在两次调用一个函数以及将返回值存储在变量之间选择哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况..我多次遇到类似情况.以下两个选项中哪一个更可取?

I have the following scenario.. and I come across the similar scenario many a times. Which is more preferable of the following two options?

选项1:

String result = ( getDetails(...) == null ) ? "" : getDetails(...);

选项2:

String returnValue = getDetails(...);
String result = ( returnValue == null ) ? "" : returnValue;

哪个更可取和/或更好的做法??

Which is more preferable and/or a good practice.?

推荐答案

选项2:更好

Option-1:会导致额外的方法调用,并且应始终避免此类情况,除非getDetails(...)是一种吸气剂方法(一种返回某些内容的线性方法)

Option-1: Results in extra method call and such cases should always be avoided unless getDetails(...) is a getter method (a one liner method which returns something)

如果您深入研究微优化,通常会导致方法调用

If you dig down to micro optimization, a method call generally results in

  • 方法变量的堆栈分配
  • 跳过指令集

这是许多间接费用中的几个. 很多人说,这种性能优化应该留给编译器和代码应该写得更具可读性.

which are couple of many overheads. As many say, such performance optimization should be left to Compiler and the code should be written to be more readable.

这篇关于在两次调用一个函数以及将返回值存储在变量之间选择哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆