Which is faster to retrieve information from, an object or a simple calculation?
Is there a notable difference between them?
Context:
- Web development
- Using js and/or jQuery
- up to hundreds of items affected on a page
Here is a sample of the object I would retrieve information from:
var pModel = {
1 : {sire: 3, dam: 4, herdList: settings.sireList},
2 : {sire: 5, dam: 6, herdList: settings.damList},
3 : {sire: 7, dam: 8, herdList: settings.sireList},
4 : {sire: 9, dam: 10, herdList: settings.damList},
5 : {sire: 11, dam: 12, herdList: settings.sireList},
6 : {sire: 13, dam: 14, herdList: settings.damList}
};
After I wrote the code, I noticed the mathematical pattern inherent in the data:
// Where x is a number
pModel[x].sire == 2x+1;
pModel[x].dam == 2x+2;
(x%2=0) ? settings.damList : settings.sireList;
There are obvious future proofing advantages to using math, but speed is a major consideration here.
At least for math that simple, it turns out math is faster:
http://jsperf.com/object-vs-calc