Note that there are some explanatory texts on larger screens.

plurals
  1. POFast way to hash objects focussing on properties containing a certain attribute?
    text
    copied!<p>I have created my own form of serialization which converts an object supplied to a string which I can then get an MD5 hash of. The hashing is used for a quick compare to see if specific properties have changed. However my code is extremely slow and I was wondering if anyone has any better ideas?</p> <p>I need to <em>only</em> worry about the properties in the object marked with a custom [DatabaseMap] attribute. I'm not too concerned about the hashing method, but rather the way the object is serialized before being hashed.</p> <p>Is there a better way of doing this?</p> <pre><code> public static string GetHash(this IBaseObject source) { if (source == null) return string.Empty; // step 1, calculate MD5 hash from input var hasher = new ThreadLocal&lt;MD5&gt;(MD5.Create); byte[] inputBytes = Encoding.UTF8.GetBytes(SerializeDataMembers(source, hasher)); // serialize the object byte[] hash = hasher.Value.ComputeHash(inputBytes); // step 2, convert byte array to hex string // StringBuilder sb = new StringBuilder(); // for (int i = 0; i &lt; hash.Length; i++) // { // sb.Append(hash[i].ToString("X2")); // } // return sb.ToString(); return BitConverter.ToString(hash); } private static string SerializeDataMembers(IBaseObject source, MD5 hasher) { StringBuilder sb = new StringBuilder(); var properties = source.GetType().GetProperties(); foreach (PropertyInfo prop in properties) { var attrs = Attribute.GetCustomAttributes(prop); if (attrs.OfType&lt;DatabaseMap&gt;().Any()) { if (prop.PropertyType == typeof (byte[])) { sb.Append(Convert.ToBase64String(hasher.ComputeHash((byte[])prop.GetValue(source)))); } else { sb.Append(prop.GetValue(source)); } } } return sb.ToString(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload