javascript - Object performance, what is better long items or many items?

I've to record some events into an json-object, so what is better from performance point of view, long or many sub-objects?

For better interpretation take a look at these two objects:

1st (long objects)

var eventsObj = {
  target: {
    timestamp1: window,
    timestamp2: document,
    timestamp3: document
  },
  keyCode: {
    timestamp1: 0,
    timestamp2: 66,
    timestamp3: 67
  },
  mouseX: {
    timestamp1: 1,
    timestamp2: 2,
    timestamp3: 3
  },
  mouseY: {
    timestamp1: 0,
    timestamp2: 1,
    timestamp3: 2
  }
  ...etc...
};

2nd (many objects)

var eventsObj = {
  timestamp1: {
    target: window,
    keyCode: 0,
    mouseX: 1,
    mouseY: 0
  },
  timestamp2: {
    target: document,
    keyCode: 66,
    mouseX: 2,
    mouseY: 1
  },
  timestamp3: {
    target: document,
    keyCode: 67,
    mouseX: 3,
    mouseY: 2
  }
  ...etc...
};

Update

http://jsperf.com/object-performance-long-items-or-many-items

2 Answers

  1. Jason- Reply

    2019-11-14

    In terms of memory consumption, both will be (almost) identical. Performance depends on how you intend to iterate and consume the object.

    However, the second representation is far more readable and semantically correct.

  2. Jeffery- Reply

    2019-11-14

    I'd say the 2nd, because you'll probably end up wih several statements including one or several loops in the first case for getting one event's data ; whereas only one 'for...in' loop in the second case will be enough for retreiving a single event's data

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>