两次调用函数与存储输出并在 Java 中使用它 [英] Calling the function twice vs. storing the output and using it in Java

查看:46
本文介绍了两次调用函数与存储输出并在 Java 中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 boolean 函数 isCorrect(Set).
该函数的参数由另一个函数buildSet()计算.

Suppose that I have a boolean function isCorrect(Set<Integer>).
The parameter of the function is calculated by another function buildSet().

在时间和空间效率方面哪个更好?

Which one is better in terms of both time and space efficiency?

Set<Integer> set = buildSet();
if(isCorrect(set))
    doSomethingWith(set);

if(isCorrect(buildSet()))
    doSomethingWith(buildSet());

推荐答案

第一种方法更好,我不认为这是见仁见智的问题.当您已经获得结果时,不要浪费地调用相同的函数两次.当然,我假设 buildSet() 没有任何必要的副作用.

The first approach is better, and I don't think this is a matter of opinion. Don't call the same function twice wastefully when you already have its result. Of course, I'm assuming buildSet() doesn't have any necessary side effects.

在时间和空间效率方面哪个更好?

Which one is better in terms of both time and space efficiency?

就时间而言,您在第一个片段中构建了一次,在第二个片段中构建了两次,所以大概第二个需要更长的时间.在空间方面,可能不会有区别.但是,您似乎在第二个片段中实例化了 两个 对象,而在第一个片段中只实例化了一个(同样,我无法确定这一点,因为我不知道 buildSet() 已实现).如果是这种情况并且您要保留这两个对象,那么第二个代码段也将使用两倍的空间.

In terms of time, you're building the set once in the first snippet and twice in the second snippet, so presumably the second would take longer. In terms of space, there likely will not be a difference. However, you seem to be instantiating two objects in your second snippet and just one in your first (again, I can't be sure of this because I don't know how buildSet() is implemented). If this is the case and you're retaining both of those objects, then the second snippet will use twice the space as well.

这篇关于两次调用函数与存储输出并在 Java 中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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