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.
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)"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With