1300000 bytes → 2572 bytes! 99% compression!
Stop wasting memory! Let’s see how you can reduce 1300000 bytes to almost 2572 bytes i.e. 99% compression!
Dart has some really powerful compression algorithms which we can use! Let’s say you have a long JSON or a string that you want to store in your local storage. Suppose the JSON is of 1300000 bytes, so when you store it in your local storage, it will occupy almost 1.3 MB of memory. Though it’s not much, a use case can occur where your data can be of 100s of MB. So, you can compress your data before storing it in local storage. Let’s see how we can do that using GZip!
So here I created a long string by iterating and appending 100000 times. Once you have the data, you need to encode it using
utf8.encode . After that, you can check the original size of the data and compress it using
If you wish to run the code, you can run using
dart run main.dart
You can see that the original data was 1300000 bytes while data after compression was 2572 bytes. That is almost 99% compression!
I tried the same with a JSON file containing 5000+ lines of data and found to get approx 86% compression. You can check the code here!
Though this was a small and simple article, it’s useful to use as it will reduce your memory occupancy a lot!
You can directly clone the file from GitHub!
Note: If you increase the for loop iteration, the program might take time to display the output or might even stop your PC!
Hope you enjoyed this article!
If you loved it, you can Buy Me A Coffee!
Don’t stop, until you are breathing!💙
- Abhishek Doshi