5

In JavaScript, with my own emulator implementation, getting the value of register field RA from a 32-bit instruction i is often represented as:

this.gpr.u32[(i >> 16) & 0x1f]

However, having the above expression many times in a function is ugly and hard to follow and edit. I have avoided defining a variable ra with that expression and using it because I thought that it would be stored in memory, and fetching it would be costly. Should I be worried about this or do modern JavaScript engines 'inline' the value of the variable into the statements that follow the definition? Though using a variable makes the code much cleaner, I don't really want to use it if it will slow down the execution time in a performance-sensitive environment such as an emulator.

1 Answer 1

6

There are a lot of "it depends" in an answer. First of all it depends on the javascript interpreter how good it can optimize.

Nevertheless, if I understand you correctly your code is something like

.... this.gpr.u32[(i >> 16) & 0x1f] ...
.... this.gpr.u32[(i >> 16) & 0x1f] ...
.... this.gpr.u32[(i >> 16) & 0x1f] ...

instead of

ra = this.gpr.u32[(i >> 16) & 0x1f];
.... ra ....
.... ra ....
.... ra ....

In this case I suppose any javascript engine will execute the latter much faster. It is true that you have an additional variable ra in memory. But access to ra should not be slower than access to i plus shift and mask plus access to this.gpr.u32.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! So what you're saying is that any unwanted access latency to ra would be heavily outdone by the unwanted access latency of fetching i, doing a shift, doing an AND, then fetching an item out of this.gpr.u32, provided that the long form is not cached somehow automatically by the engine.
@Delan Azabani: More or less. It is much easier for an engine to inline a single variable than the overall expression and thus I suspect that most engines are much better in the former.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.