再次调用一个函数要比将其分配给变量更好 [英] Calling a function again better than assigning it to variable

查看:58
本文介绍了再次调用一个函数要比将其分配给变量更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否在类中调用了一个getter函数,该函数的计算性能并不比为新变量赋值更好?

Is calling a getter function in class that does not computation better than assign value to a new variable?

示例:

Class Test{
        private AnotherClass a;
        public AnotherClass getA(){
            return a;
        }
}

最好继续在同一个函数中调用getA()还是执行AnotherClass var1 = getA(); 然后继续在该函数中使用var1.

Is it better to keep calling getA() in a same function or todo AnotherClass var1 = getA(); then keep using var1 in that function.

我想了解内存与性能&我们该如何平衡呢?

I want to understand memory vs performance & how can we balance it.

用法示例: 考虑列出另一个班级

Usage example: Consider another class being list

    AnotherClass var1 = test.getA();
    if(var1!=null){
    for(List var : var1){
// do something
}

or 

if(test.getA()!=null){
for(List var : test.getA())
// do something
}

请注意,这种行为可以在多个地方多次执行.

Note this kind of behaviour can be done multiple time in multiple places.

推荐答案

看到此问题:通常,您应该为可读性而不是性能进行编码.编译器很可能会为您优化get()调用.如果不是这样的话,那么事实证明这是个问题,您可以在完成代码识别和消除瓶颈后随时对其进行概要分析.首先,绝对要提高可读性.

In general, you should code for readability rather than performance. The compiler may very well optimize away get() calls for you. If it doesn't, and this turns out to be an issue, you can always profile your code after it is finished to identify and eliminate bottlenecks. To start off, though, definitely go for readability.

这篇关于再次调用一个函数要比将其分配给变量更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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