r/javascript • • Jul 28 '15

I'm all in.

Post image
746 Upvotes

120 comments sorted by

View all comments

Show parent comments

5

u/jkoudys Jul 29 '15

You are, a little. There's two basic datastructures that nearly every js app is going to use: the Array, and the Object. An array is a little closer to its classic definition than, say, PHP's array is, but it's far from what an "array" is in C, and meant in general to represent any mutable dataset ordered by index. An object, conversely, has no predefined order, and it's just a hashmap (this is what JSON -- technically a separately defined format -- loads as). Even if you have an object {a: 'foo', b: 'bar', c: 'baz'}, it technically has no order, and without logic around it to enforce the behaviour, you can't rely on property "a" coming before property "b".

If you're in a language like C or Java, much of the syntax and libs are dedicated to defining data structures based on their low-level behaviour. The syntax in JavaScript is focused more on high-level behaviour: the logic that your datastructure should follow as observed by those calling it. So as a JavaScript developer, you can look at a fairly complex dataset defined in JSON, but it's not necessarily optimized to run very quickly for what you're doing.

I am noticing that this is changing quite a bit. In addition to the upcoming harmony datastructures /u/Klathmon mentions (Map and Set), there have also been TypedArrays out for a while. These look more like traditional arrays, which simply define an extent (over an arraybuffer), and then the Unit8Array or Float64Array, etc. you define simply defines how to iterate it and compute offsets within the buffer. I'd recently started using it to do some low-level work in rewriting a gameboy emulator as modern es6 JavaScript with ReactJS, and these TypedArrays were perfect for modelling a memory space with 8-bit registers: https://github.com/jkoudys/ReactGB/blob/master/js/utils/emulator/z80.js#L43

All that said, the v8 engine and its JIT can be downright magical, in both the best and worst possible ways. Sometimes it figures out exactly what you mean when you setup a more complex datastructure, and other times a tiny change takes efficient processing down to garbage. Probably the worst thing for it to figure out is in pruning trees and removing nodes -- downright trivial on a good C implementation, with simple pointers, but taking a large array (or even object) and deleting nodes can confuse the hell out of v8.

1

u/Ehdelveiss Jul 29 '15

Thank you for your detailed reply! That helps me understand much better :)