2

There are situations where we can store values in local variables and work with them. For example:

String data;
int a, b;

data = Integer.toHexString(memory.read(PC));
a = ("00" + data).substring(data.length());

data = Integer.toHexString(memory.read(PC + 1));
b = ("00" + data).substring(data.length());

Or we can just make multiple function calls to achieve the same thing:

a = ("00" + Integer.toHexString(memory.read(PC))).substring(Integer.toHexString(memory.read(PC)).length());
b = ("00" + Integer.toHexString(memory.read(PC + 1))).substring(Integer.toHexString(memory.read(PC + 1)).length());

Which one is better from the performance point of view?

Deduplicator
  • 9,031

3 Answers3

3

Go with the version that's easiest to read and understand.

I agree with Alex's answer - it's very unlikely that there will be a measurable difference in performance between the two versions.

However, even if there was a difference you can easily lose all of those gains while the app is down and you're trying to debug it.

Dan Pichelman
  • 13,813
2

There is a performance difference. Integer.toHexString(memory.read(_)) is called 2 times in the first example, and 4 times in the second example. Since your question was more about the general case, if using the variables causes half the calls to occur, and the calls are slow (not in this specific case), it can be twice as slow to use the first method.

It is personal taste, but I prefer the common sub-expressions to be factored out using local variables, both to ensure they have the same value in all places referenced, and to make the common nature of the sub-expression more clear.

1

The best way to answer the question is to put both fragments into large-ish loops and time them a few times.

The unscientific answer is that it's fairly unlikely (in Java) that they'll differ in performance all other things being equal. During the compilation process, the compiler will likely convert the unassigned method calls to assignments to temporaries anyway. As such, the two will end up being identical (plus or minus some statement permutations) and end up as equivalent bytecode.

You also have C as a tag. As this is definitely not C code, I can't really comment on what would happen in C. You could conceivably write this in C++ but then the answer would depend a lot on the definition of the String class, amongst others, so this can't be answered in general.

Alex
  • 3,922
  • 1
  • 15
  • 16