I am using a lot of ajax calls to query the database and I get large text (json) responses. I will like to compress the response.
There is a great way of compressing text using javascript in JavaScript implementation of Gzip.
The problem is I want to compress the response on my aspx server and decmpress it with javascript. Therefore I need to run the lzw_encode
function on my asp.net server. Should I I translate that function to C# or there is another way?
Using the link above if you dont want to configure IIS or change header you can compress the code on the server with:
C#
public static string Compress(string s) { var dict = new Dictionary<string, int>(); char[] data = s.ToArray(); var output = new List<char>(); char currChar; string phrase = data[0].ToString(); int code = 256; for (var i = 1; i < data.Length; i++){ currChar = data[i]; var temp = phrase + currChar; if (dict.ContainsKey(temp)) phrase += currChar; else { if (phrase.Length > 1) output.Add((char)dict[phrase]); else output.Add((char)phrase[0]); dict[phrase + currChar] = code; code++; phrase = currChar.ToString(); } } if (phrase.Length > 1) output.Add((char)dict[phrase]); else output.Add((char)phrase[0]); return new string(output.ToArray()); }
and on the browser you can decompress it with:
javascript
// Decompress an LZW-encoded string function lzw_decode(s) { var dict = {}; var data = (s + "").split(""); var currChar = data[0]; var oldPhrase = currChar; var out = [currChar]; var code = 256; var phrase; for (var i = 1; i < data.length; i++) { var currCode = data[i].charCodeAt(0); if (currCode < 256) { phrase = data[i]; } else { phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar); } out.push(phrase); currChar = phrase.charAt(0); dict[code] = oldPhrase + currChar; code++; oldPhrase = phrase; } return out.join(""); }
The REST API compresses the response if the client properly specifies this header. The response includes the header Content-Encoding: gzip or Accept-Encoding: deflate . You can also compress any request by including a Content-Encoding: gzip or Content-Encoding: deflate header.
Gzip has a high compression ratio around 95% with CSV and JSON.
One of the more frequently asked questions about the native JSON data type, is what size can a JSON document be. The short answer is that the maximum size is 1GB.
Within your server-side response object add a header for GZip, like this:
Response.AddHeader("Content-Encoding", "gzip");
Also, you can use the GZipStream class to compress your content, like this:
Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);
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