1

How does LokiJS compare in regards to standard javascript object access by key?

var obj = {};

for (var i = 0; i < 10000; i++) {
    obj[i] = { name: 'name', description: 'desc', misc: 'misc' };
    lokicollection.insert({ id: i, name: 'name', description: 'desc', misc: 'misc' });
}

Would accessing the object directly by key have any performance benefits by using LokiJS?

alert(obj[id].name);
alert(lokicollection.by('id', id).name);

Would enumerating the object have any performance benefits by using LokiJS?

var item, arr = lokicollection.where(function(obj) { return true });
for (var i = 0; i < arr.length; i++) {
    item = arr[i];
}

var item, keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
    item = obj[keys[i]];
}
wayofthefuture
  • 8,339
  • 7
  • 36
  • 53
  • 1
    Take it and measure. If you cannot measure it reliably - then it does not matter. – zerkms May 07 '16 at 01:57
  • 1
    You can use your browser's developer tools or local profiling tools to compare performance. That's the only way to get a reliable answer for the environment you are interested in. – Felix Kling May 07 '16 at 01:58

1 Answers1

2

Aside from the very valid comments about dev tools and ad-hoc benchmarking, the bottom line is that performance on data structures in JS cannot easily be generalized. Sparse array don't perform as well as dense ones, mixed type arrays don't perform as well as single-type ones because the underlying engine tends to intelligently optimize based on the data contained in your arrays. LokiJS is fast, and it is optimized to use uglier but faster iterations (e.g. for-loops instead of forEach) and to keep arrays dense, but ultimately LokiJS does a lot more in the background: indexing, computing views, emitting events etc. These operations come at a performance cost, a cost that a simple array insertion operation does not have. The usefulness of a solution like LokiJS is in fast retrieval of filtered/sorted data, and background re-computation of views (as well as the ability to persist data to disk/localstorage/indexeddb). So unless you need persistence and have a load of data to manage I don't think you will really gain performance from LokiJS. This from the person that wrote LokiJS ;)

Joe Minichino
  • 2,793
  • 20
  • 20
  • Wow! Would you consider 10,000 items (10 fields each) a "load" of data? Great job btw! – wayofthefuture May 07 '16 at 14:52
  • @Dude2TheN yeah that looks like a lot of data! Thanks! – Joe Minichino May 07 '16 at 16:33
  • So I was thinking when it comes to enumerating the entire set, there could be some slowdown specifically with the item=arr[i]; line, because for every iteration it has to lookup the object property. Any thoughts on how to improve performance of that with Loki? – wayofthefuture May 07 '16 at 16:59