Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use String or Date as an object key for memoization.

I have an array of dates and I need to perform some computations for these date more than once. So I decided to use memoization to cache results.

However, I'm not sure if it's okay to use Date object as a key. I expect that comparing dates could be slower than comparing strings, so maybe it makes sense to use string representation of date as a key.

So my question is, which is better to use as key, string or date, to access value in JavaScript object.

like image 479
evfwcqcg Avatar asked Apr 07 '13 11:04

evfwcqcg


1 Answers

I think you could use the getTime method instead, to compare the numeric version of your Date object. Should be faster, plus is more reliable IMVHO of the string representation across browsers and SO, with their locales, and can be easier to be manipulated too.

If you're not using Map or WeakMap but just plain objects, notice that passing a Date object as key of an object will automatically get it's string version (toString will be called):

var now = {}; 
now[new Date()] = true;


console.log(Object.keys(now)); // ["Sun Apr 07 2013 13:21:17 GMT+0200 (CEST)"]
like image 174
ZER0 Avatar answered Nov 15 '22 00:11

ZER0