Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

Is it useful to compress localStorage?

I'll start off with a solid example: I have a function that generates hashes (32-bit integers) and saves them in localStorage. This is to implement a "don't show me again" feature for common notifications: if the hash is in the list, don't show the notification.

After my first attempt at coding this solution, my localStorage entry looked like this:

616845040,796177849,848184043,1133088406,1205053317,1478518197,1525440546,1686606993,1753347541,1908577591,2056496592,-864967541,-1185668678,-835401591,-1017499054,-559563441,-1842092814,-1069291933,-1887162563

19 hashes, 210 bytes of data.

A little later, I revisited the code. Instead of just dumping the integers as decimal strings, I converted them into actual binary data. In other words, each hash is now a string of four characters in length representing the binary value of the integer. My localStorage entry now looks like this:

$ÄNð/tµ¹2BëCGÓ§X eµZì`"dhõÕqÂ7z¥Ðᅩq¤ᄍT!ºᅫ4ÈᅢZ2R￞¥½Oメ3äò￀Cæcマ/=

19 hashes, 76 bytes of data (There's some non-printable characters in there)

That's a savings of 63.8%.

Now, I am well aware that localStorage provides, by default, 5MB of storage space. I could easily store tens of thousands of hashes with the first method with no issues at all. But I like being efficient. I certainly wouldn't want a 5MB file on my computer when I could have the same data in 1.8MB (same compression ratio as above). That's why I save all my PNGs as indexed-palette when possible.

Is this a good mentality to have? Or am I just being pedantic? I guess this question could be summarised as: Should I compress, or just not care due to having more resources than I'll ever need?

Upvotes: 1

Views: 913

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174937

Pedantic is good when coming to code. Compress when you can, but be sure that when reading your code, it's still readable and understandable that hashes are kept in whatever way.

What I mean is, don't sacrifice your code readability and maintainability for efficiency.

Upvotes: 1

Related Questions