再次将值存储为变量或调用方法更好吗? [英] Is it better to store value as variable or call method again?

查看:86
本文介绍了再次将值存储为变量或调用方法更好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我开始学习一些Java.根据我对JVM的了解,JIT使其在需要CPU周期(即调用方法)的操作中非常快,但也使其渴望内存.因此,当我需要与以前相同的方法输出相同的输出时,通常是否更好的方法是将before的输出存储在变量中并再次使用-始终将其保留在内存中-还是再次调用相同的方法?

Recently, I started learning some Java. From what I've already learned about JVM it looks like JIT makes it pretty fast on operations requiring CPU cycles (i.e. calling a method) but also makes it hungry for memory. So when I need same output from same method as before, is it generally better approach to store the output from before in variable and use it again - while holding it in memory all this time - or call the same method again?

推荐答案

更好的做法是将输出保存在变量中,而不是再次调用该函数.该变量将根据需要保留在内存中.之后,自动垃圾收集将负责将其从内存中释放出来.但是,如果调用该函数,则每次调用该函数时,它将耗尽其激活记录堆栈的内存.因此,如果您不希望程序占用内存,最好将结果存储在变量中,并在需要的地方使用它.

It is better practice to hold the output in a variable rather than calling the function again. The variable is going to be held in memory as long as it requires. After that automatic garbage collection will take care of that to free it up from the memory. But if you call the function, it will eat up the memory for its activation record stack each time it gets called. So if you want your program not to be memory hungry, its better to store the result in a variable and use it wherever it is required.

这篇关于再次将值存储为变量或调用方法更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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