views:

162

answers:

4

I have a big dictionary where the key is decimal, but the GetHashCode() of System.Decimal is disasterously bad. To prove my guess, I ran a for loop with 100.000 neigboring decimals and checked the distribution. 100.000 different decimal numbers used only 2 (two!!!) different hashcodes.

Decimal is represented as 16 bytes. Just like Guid! But the GetHashCode() distribution of Guid is pretty good. How can I convert a decimal to Guid in C# as cheap as possible? Unsafe code is OK!


EDIT: The test was requested, so here is the code:

        decimal d = 96000000000000000000m;
        Dictionary<int, int> hashcount = new Dictionary<int, int>();
        int length = 100000;
        for (int i = 0; i < length; i++)
        {
            int hashcode = d.GetHashCode();
            int n;
            if (hashcount.TryGetValue(hashcode, out n))
            {
                hashcount[hashcode] = n + 1;
            }
            else
            {
                hashcount.Add(hashcode, 1);
            }
            d++;
        }

        Console.WriteLine(hashcount.Count);

This prints 7. I do not remember the starting decimal that gave me 2.

+1  A: 

Convert your decimal value to byte array, and then create a guid from it:

public static byte[] DecimalToByteArray (decimal src) 
{
    using (MemoryStream stream = new MemoryStream()) 
    {
        using (BinaryWriter writer = new BinaryWriter(stream))
        {
            writer.Write(src);
            return stream.ToArray();
        }
    }
}

Decimal myDecimal = 1234.5678M;
Guid guid = new Guid(DecimalToByteArray(myDecimal));
Nissim
Your code wont compile, the last statement is nonsensical.
leppie
While I bet it works, it does not look fast. This code is to be used in a dictionary!
Dude, if you want it to work fast - say it! don't immediately give a down vote... people are here to help you. My solution answer you question - nowhere in your question did you say it HAVE to be fast.
Nissim
By the way - I tested it on 100000 values and it took 00:00:00.0754544 seconds (75 ticks) - believe me - that's fast enough
Nissim
I did say "cheap". And I did not vote it down. It was someone else.
@user: while Nissim's answer certainly wouldn't be fast, i doubt that *anything* will be very fast for this. Are the keys being generated each time you create the dictionary, or are they static bits of data (ie keys from some data source)?
slugster
[Sorry about the downvote.](http://meta.stackoverflow.com/questions/62219/)
Timwi
A: 

The distribution of GUID is good as it is meant to be unique...

What is the range of numbers used for this? The default GetHashcode() implementation for Decimal might only take a certain range of values into consideration.

leppie
+10  A: 

EXTREMELY HACKY SOLUTION (but probably fastest possible)

public static class Utils
{
    [StructLayout(LayoutKind.Explicit)]
    struct DecimalGuidConverter
    {
        [FieldOffset(0)]
        public decimal Decimal;
        [FieldOffset(0)]
        public Guid Guid;
    }

    private static DecimalGuidConverter _converter;
    public static Guid DecimalToGuid(decimal dec)
    {
        _converter.Decimal = dec;
        return _converter.Guid;
    }
    public static decimal GuidToDecimal(Guid guid)
    {
        _converter.Guid = guid;
        return _converter.Decimal;
    }
}

// Prints 000e0000-0000-0000-8324-6ae7b91d0100
Console.WriteLine(Utils.DecimalToGuid((decimal) Math.PI));

// Prints 00000000-0000-0000-1821-000000000000
Console.WriteLine(Utils.DecimalToGuid(8472m));

// Prints 8472
Console.WriteLine(Utils.GuidToDecimal(Guid.Parse("00000000-0000-0000-1821-000000000000")));
Timwi
Hmmmmmm, I always thought overlapping fields to only apply when crossing native boundaries. Wow, it works! Learnt something new today :) +1
leppie
WAAAAAOOOOO, this is genius!Studying the Guid.GetHashCode() in Reflector, hashvalue depend primarily on the first 8 bytes of the Guid. While in the decimal, the first 8 bytes varry the least. Any idea, how to reverse the byte order, or swap the first and the last 8 bytes?
@user256890: `Array.Reverse` might be a start...
leppie
@user256890: Since you want it as fast as possible, just use the same trick again: http://csharp.pastebin.com/Jqg9F9HA
Timwi
+5  A: 

If you're just trying to get a different hash algorithm, there's no need to convert to a Guid. Something like this:

public int GetDecimalHashCode(decimal value)
{
    int[] bits = decimal.GetBits(value);
    int hash = 17;
    foreach (int x in bits)
    {
        hash = hash * 31 + x;
    }
    return hash;
}

(Obviously substitute a different algorithm if you want.)

Admittedly this still involves creating an array, which isn't ideal. If you really want to create a Guid you could use the code above to get the bits and then a long Guid constructor passing in appropriate values from the array.

I'm somewhat suspicious of the decimal hashcode being so bad though. Do you have some sample code for that?

Jon Skeet
How would you use this when storing `decimal` values in a dictionary? Surely the dictionary will invariably use the original `decimal::GetHashCode()`?
Timwi
Just pass your custom IEqualityComparer in dictionary constructor
digEmAll
@Timwi But the hashcode **doesn't have to be unique** within a dictionary, so that wouldn't matter so much.
Rowland Shaw
@Rowland: sure, but dictionary performances decrease with bad hashing (the famous ~O(1) key-lookup time will only work with very good hashing)
digEmAll
@Rowland: I don’t see how your comment relates to mine at all.
Timwi
@Timwi I was responding to the fact that the dictionary would refer to decimal's `GetHashCode()` - whilst not brilliant (if the OP's sample data is distributed in a similar manner to their test data), it would still *work*, so it maybe a case of worrying unduely which implementation gets called.
Rowland Shaw
@Rowland: Did you read the question at all?
Timwi