I was wondering if there is a difference in efficiency or performance when working with temporary variables inside constructors or methods.
Here is an example
// Get bufferedImage
BufferedImage trayIconImage = ImageIO.read(getClass().getResource("/images/D.gif"));
// Calculate width
int trayIconWidth = new TrayIcon(trayIconImage).getSize().width;
// Create TrayIcon
TrayIcon trayIcon = new TrayIcon(trayIconImage.getScaledInstance(trayIconWidth, -1, Image.SCALE_SMOOTH));
So I have a temporary variable "trayIconWidth"
But I also could do this like so:
//Get bufferedImage
BufferedImage trayIconImage = ImageIO.read(getClass().getResource("/images/D.gif"));
// Create TrayIcon
TrayIcon trayIcon = new TrayIcon(trayIconImage.getScaledInstance(new TrayIcon(trayIconImage).getSize().width, -1, Image.SCALE_SMOOTH));
So basically I am skipping the step of getting the int value for the width.
There are a lot of examples where you can skip multiple temporary variables and I know that it has to do with readability and stuff. But I would like to know if there is any difference in speed, performance, efficiency, or ram usage.
Does the (e.g. java) garbage collector handle this kind of temporary action?
EDIT 1:
I compared the bytecode of two basic snippets. They are different. second
So this means the pc has to do one or more instructions to get the execution done - am I right?
regards Nur1
The byte-code is going to be different, yes. In the case where you use that String s = "Hello World"
, there is going to be two more bytecode instructions: astore_1
and aload_1
, for storing into s
and then reading from s
.
But that happens only at the byte-code level. Though there is no needed for s
at all, javac
does not do any optimization (or better said - does very, very little) and does not elide that away. It's JIT
duty to make these, and the removal of local s
is trivial for it to make. So while the idea is correct that - "there is more work to do" with the second version, this "more" can not even be measured of how small it is. It's like taking a hot cup of water in Siberia in December outside and saying that the temperature outside has changed because of that hot cup of water. Yeah, it did change for sure, but that is impossibly small to measure.
Hi, thanks - this is actually informative enough to mark it as the solution. But what about the RAM usage? Like when a thread does something several times with those temporary vars. Wouldnt it affect the performance at any point? I guess ill try and benchmark it.
@Nur1 the entire stack of a thread is allocated when the thread is created. Creating more local variables may turn a few bytes of it from unused to used, but most of the time, the majority of this pre-allocated stack space is unused anyway. As long as you don’t get a
StackOverflowError
, your additional local variables had no effect.