Int array as a key in a Dictionary VS a string

I have a dictionary right now that is using a string as the Key, and a GameObject as the value.

The strings are all IP address's, so they are not very long. Here is an example:

string ip = "192.68.137.1"

I know that number comparisons are much faster than strings, and I am able to parse the IP address's in my database server.

Would it be faster to use an integer array as the KEY for the dictionary? Like this:

int[] ip = { 192, 168, 137, 1 }

I am checking if the dictionary contains certain values on a regular basis, and also adding to the dictionary regularly (At least once a second normally).

The reason that I am confused about this is because the strings that I am using (the IP address's) are always going to be around that length, so would there be any real benefit to using an integer array? If the dictionary would have to loop through 4 numbers every time, I don't know how much faster that is than a string comparison.

Jon Skeet
people
quotationmark

As ever, you should test performance rather than guessing about it or asking others to guess. However, two things to think about:

  • You've shown an IPv4 address... what about IPv6? That could definitely complicate things
  • The IPv4 address is really 4 bytes... so why not convert that into a single uint or IPAddress as the key? That way you don't need to write your own EqualityComparer<int[]>. It's a shame IPAddress doesn't implement IEquatable<IPAddress>, but it looks like it does override Equals/GetHashCode appropriately.

I'd consider the first point, write detailed benchmarks which work out how important this really is - if you're really only looking up about once per second, it's very unlikely to be important at all - and then try the various options. I would only move away from the simplest code (which would be a string if that's how you're already receiving the IP address) if you can show a proven, significant improvement.

people

See more on this question at Stackoverflow