Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'inlining' in JavaScript?

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.

like image 984
Delan Azabani Avatar asked May 22 '11 09:05

Delan Azabani


1 Answers

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.

like image 140
Howard Avatar answered Sep 27 '22 18:09

Howard