1
  1. In Javascript I can represent a 2D point (1,2) either as an object {x:1, y:2} or as an array [1,2]. Is the last one significantly better when it comes to performance?
  2. If at some point of my program I decide to add a property to a point v (such as v.next = u) and v is represented as an array, will I loose that [*] performance gain?

[*] assuming the answer to 1 is YES.

stag
  • 71
  • 1
  • 3
  • In javascript everything is an object, even the arrays, so I see no difference, do what is easier to code maintain – Itay Moav -Malimovka Sep 23 '14 at 20:18
  • Well, but in practice I think that indexing an array is much faster than accessing an object's field (since the later requires some kind of hashing and the former is really a memory access, provided that the array is not sparse and it's a "real" array (not just an object with numerical fields)) – stag Sep 23 '14 at 20:24
  • I mean, maybe by the standard everything is the same thing, but I really think (or hope that) a javascript engine doesn't make a hash lookup at each array access. – stag Sep 23 '14 at 20:27
  • Check this question out for some info: http://stackoverflow.com/questions/17295056/array-vs-object-efficiency-in-javascript – Teeknow Sep 24 '14 at 00:14
  • After reading http://www.html5rocks.com/en/tutorials/speed/v8/ , I think that this depends on a lot of code details that control how much optimization the engine can/will do. So you really have to talk about specific code, at which point you might as well just ask jsperf. – Ed Staub Dec 05 '15 at 17:06

1 Answers1

0

Taking my own advice (comment above), googling for 'array object point site:jsperf.com' leads to http://jsperf.com/point-array-vs-point-object/2 , which suggests that, at least in Chrome and Node.js (V8) today, objects may be be the better choice.

But if I wanted to put the pedal to the metal and was mostly working with arrays of points, I'd also benchmark code that forces all args to integers (x=x|0) and uses a one-dimensional array, performing the address arithmetic for x/y by hand, and writing an ES6 iterator for it. If done carefully, this can avoid creating an object for most points, even when manipulating them.

Ed Staub
  • 15,480
  • 3
  • 61
  • 91