caching - How should a cache key be created from multiple keys? -
i have method output i'll caching. takes 4 parameters; string
, string
, int
, , windowsidentity
. need create cache key based on 4 parameters. best to:
concatenate them strings , use key?
var key = string.concat(string1, string2, int1.tostring(), identity.tostring());
or
xor hash codes?
var key = string1.gethashcode() ^ string2.gethashcode() ^ int1.gethashcode() ^ identity.gethashcode();
or else? matter? in particular case, these keys going hashtable (c# v1).
create new type encapsulates 4 values. example:
public sealed class user { private readonly string name; private readonly string login; private readonly int points; private readonly windowsidentity identity; public user(string name, string login, int points, windowsidentity identity) { this.name = name; this.login = login; this.points = points; this.identity = identity; } public string name { { return name; } } public string login { { return login; } } public int points { { return points; } } public windowsidentity identity { { return identity; } } public override bool equals(object other) { user otheruser = other user; if (otheruser == null) { return false; } return name == otheruser.name && login == otheruser.login && points == otheruser.points && identity.equals(otheruser.identity); } public override int gethashcode() { int hash = 17; hash = hash * 31 + name.gethashcode(); hash = hash * 31 + login.gethashcode(); hash = hash * 31 + points.gethashcode(); hash = hash * 31 + identity.gethashcode(); return hash; } }
note assumes windowsidentity
overrides equals
, gethashcode
appropriately - or you're happy reference type equality.
this approach lot more robust either of suggestions - example, in first approach 2 string pairs "xy", "z" , "x", "yz" end forming same cache key (if int , identity same) whereas shouldn't. second approach more lead accidental hash collisions.
Comments
Post a Comment