Faster when I save the result of a method in a new variable?

I was wondering if it is any helpful helpful for the performance (next to the readability) when I save the result of a method in a new variable for further uses. My thought was, that like this the method only needs to be processed once or is this a misunderstanding and only a waste of memory?

Here I save the result of a method because I will use it multiple times.

  byte[] headerAsArray = getHeaderByteArray(currentResponse.getHttpResponse(), currentResponse.getOriginalHost(), currentResponse.getOriginalURI());
        bb.writeInt(headerAsArray.length);
        bb.writeBytes(headerAsArray);
Jon Skeet
people
quotationmark

If you mean you're trying to avoid getHeaderByteArray from being called multiple times, then yes, you're doing exactly the right thing. The "cost" of having one extra local variable is negligible in almost all cases. I'd say it's also more readable than the alternative of:

bb.writeInt(getHeaderByteArray(currentResponse.getHttpResponse(), currentResponse.getOriginalHost(), currentResponse.getOriginalURI()).length);
bb.writeBytes(getHeaderByteArray(currentResponse.getHttpResponse(), currentResponse.getOriginalHost(), currentResponse.getOriginalURI()));

That's awful! It might also be incorrect, if for some reason getHeaderByteArray() can return different results for each call. (Unlikely in this case, but possible in general. There's a big difference between calling System.currentTimeMillis() twice, and calling it once and using the result twice, for example.)

I would probably refactor it further though, by adding a method accepting whatever the type of currentResponse is. Then you can change your code to:

byte[] header = getHeaderBytes(currentResponse);
bb.writeInt(header.length);
bb.writeBytes(header);

If you find yourself writing code like this a lot though, you might also want to write a method which accepts a byte array and writes the length and then the bytes. At that point you could write:

writeDataWithLengthPrefix(getHeaderBytes(currentResponse));

people

See more on this question at Stackoverflow