Description | String compression |
---|---|
Author(s) | Pieroxy, minor adjustments by Alexis Jazz |
Updated | July 11, 2022 |
Source | User:Alexis Jazz/lz-string.js |
lz-string (made by Pieroxy) can be used to compress strings. The version used was originally licensed WTFPL version 2. Currently Pieroxy uses the MIT License for all versions.
This is particularly useful for some userscripts as localStorage is typically limited to about 5MB. Example:
window.foo = LZString.compressToUTF16('Lorem ipsum dolor sit amet');LZString.decompressFromUTF16(window.foo);
This version is based on lz-string-1.4.4/libs/lz-string.min.js
. The following changes were applied: compressToUint8Array and decompressFromUint8Array were stripped and a comment to stop JSHint from complaining was added.
This is NOT a standalone userscript! Don't bother "installing" it, this is only a resource for script authors.
Benchmark / pako
editLibrary size (min+gzip) | Compression ratio (UTF16) | Compression ratio (base64) | Compression speed | Decompression speed | |
---|---|---|---|---|---|
lz-string | ~1400 bytes | + | - | - | + |
pako | ~14K (10 times more) | n/a | + | + | + |
Benchmark to compare lz-string to mw.deflate/pako:
mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Alexis Jazz/lz-string/bench.js&action=raw&ctype=text/javascript');
Pako is faster (for compression, decompression is roughly as fast) and reaches a higher compression ratio (in base64 mode, for UTF16 localStorage lz-string is frequently more efficient). But the pako library (after min and gzip) is about 10 times bigger (only ~14K but still) and MediaWiki currently only includes the deflate side of it. (phab:T312720) To decompress content compressed with mw.deflate you need, err, an older version of pako_inflate.min.js I think. The developer in their infinite wisdom removed base64 support and doesn't provide a wrapper to implement the removed functionality. I can't fathom why anyone would want Uint8Arrays for this, you can't store them? There's a reason I stripped that stuff from lz-string for gadget use. This means any recent version of pako effectively scores DNF making lz-string the winner by default in this comparison.
Finding large localStorage objects snippet
editfor (int=0;int<Object.keys(window.localStorage).length;int++){
if ( window.localStorage[Object.keys(window.localStorage)[int]].length > 128 ) {
console.log(window.localStorage[Object.keys(window.localStorage)[int]].length+' '+Object.keys(window.localStorage)[int]);
}
}