Warm tip: This article is reproduced from serverfault.com, please click

Efficiency of temporary variables (e.g java)

发布于 2020-11-28 09:41:48

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. enter image description here second enter image description here

So this means the pc has to do one or more instructions to get the execution done - am I right?

regards Nur1

Questioner
Nur1
Viewed
0
Eugene 2020-11-28 20:49:38

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.