3 ms·
That's almost the exact scenario I am talking about. Your custom type there is perfect in JS. The JIT will VERY quickly determine that i is always an integer (
by Klathmon 10y ago
That's almost the exact scenario I am talking about.
Your custom type there is perfect in JS. The JIT will VERY quickly determine that i is always an integer (actually before the code is first run it will have figured it out), and will "unbox" that to treat it as such (and not a JS "number" type). Objects in JS have a "hidden class" where they can be stamped out literally just like the C# example, so the JIT will be working with the exact same thing. A memory-mapped custom type.
Read up on "Hidden classes" [0] which can give you some insight into how it works. Basically as long as you treat a JS object like you'd treat that C# "custom type" (don't dynamically add or remove properties, stick to one type per property), it will instantly treat it identically to how C# would treat it until it changes (at which point it bails out and tries again, and if that happens too much, it will then default back to fully-dynamic).
But even if that weren't the case, you could still write your own data storage in JS that works like that. You could do something like this:
const customType = new Uint32Array(3)
const A = customType[0]
const B = customType[1]
const C = customType[2]
That storage will not only be typed, but will also have LESS overhead than the C# example, at the expense of clarity (after all, that's basically a C array there). This is basically how asm.js works, and what the code looks like when you compile C code into JS. Obviously you don't want to do that in most cases, but if the JS engine is your bottleneck and your data storage is causing slowness, then it might help.
JITs have come a LONG way in the past 5-10 years. It's pretty incredible what they can do, and it's actually not that hard any more to make smaller functions that can run at C speeds in V8 and SpiderMonkey.
[0] https://github.com/v8/v8/wiki/Design%20Elements https://github.com/v8/v8/wiki/Design%20Elements