views:

139

answers:

2

I have a form with a textarea that can contain large amounts of content (say, articles for a blog) edited using one of a number of third party rich text editors. I'm trying to implement something like an autosave feature, which should submit the content through ajax if it's changed. However, I have to work around the fact that some of the editors I have as options don't support an "isdirty" flag, or an "onchange" event which I can use to see if the content has changed since the last save.

So, as a workaround, what I'd like to do is keep a copy of the content in a variable (let's call it lastSaveContent), as of the last save, and compare it with the current text when the "autosave" function fires (on a timer) to see if it's different. However, I'm worried about how much memory that could take up with very large documents.

Would it be more efficient to store some sort of hash in the lastSaveContent variable, instead of the entire string, and then compare the hash values? If so, can you recommend a good javascript library/jquery plugin that implements an appropriate hash for this requirement?

+1  A: 

An MD5 hash is often used to verify the integrity of a file or document; it should work for your purposes. Here's a good article on generating an MD5 hash in Javascript.

JacobM
Useful information, but if I don't need to bother with this, as the other answer suggested, then it's a little less code that I have to maintain.
user4815162342
A: 

I'm not sure computing MD5 hashes of long strings will give you better performance than storing the strings themselves. Infact, I'd be very surprised if better performance was achieved.

Unless you're including huge extracts of the Bible in these articles, saving the articles as strings won't consume large amounts of memory.

I would also strongly consider using a poor-mans comparison; and just comparing the length of the 2 strings, to see if they have changed or not, rather than actual string comparisons.

Matt
Okay, let's say the user wanted to post a chapter of a novel instead. About how long would the articles have to be to considered the length of a "huge extract of the Bible"?
user4815162342
MD5'ing the string, then comparing that to the "previous" md5 sum, takes 382ms. Basic string comparison takes 0ms; this is using a string that is ~10000 words long. (http://www.jsfiddle.net/DjM8S/)
Matt
Thank you. This is the better answer of the two, and the sort of answer I was looking for (although the other answer is informative as well). I'd vote for it, but apparently as a new user I don't have enough reputation.
user4815162342