0

I'm currently implementing an emulator in Javascript, the memory model of the emulated platform is rather complex, so I'm having my reads and writes go via an array of functions, for example:

var MRead = [];
ReadBiosSpace = function(addr) { return (EnableBios ? BIOS[addr] : ROM[addr]); };
for (i = 0; i <= 0xFF; i++) { MRead[i] = ReadBiosSpace; };
function Read(addr) { return MRead[addr](addr); };

because obviously the Read and Write functions will be called extremely often (at least once per instruction, the main execution is Operators[Read(ProgramCounter)]() ) they are extremely performance sensitive.

Are there any performance optimizations that can be done? is this the best method?

Fascia
  • 732
  • 6
  • 17

2 Answers2

1

If EnableBios doesn't change very often then the only obvious enhancement I can see is to have two different versions of ReadBiosSpace and reassign the appropriate one to those first 256 locations each time it changes.

That'll avoid having to invoke the ternary operator each time one of those locations is accessed.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • EnableBios doesn't change often at all (infact only changes once) so that's actually a good idea, that said there are areas of memory where the pointers are likely to change frequently. – Fascia Nov 02 '12 at 15:48
1

In addition to the other answers, you can use this as well:

for (i = 0xFF - 1; i--) { MRead[i] = ReadBiosSpace; };
David G
  • 94,763
  • 41
  • 167
  • 253
  • Well the for loops are only run once when the script is loaded to populate the arrays, but that's a much cleaner syntax so I'll adopt it! – Fascia Nov 02 '12 at 16:17