As one of the more experienced C# coders in his group, Yakir is often asked programming questions. Recently, his colleague James asked him the best way to store hundreds of thousands of items in memory, to which Yakir replied "It depends on how you want to access your data. If you want to access your data by index, you should store it in an ArrayList. If its easier to store things as a key-value pair, then you should use a Hashtable."

James' particular application called for a Hashtable, so he decided to implement that. A few hours later, however, he ran into some trouble. "This Hashtable isn't really working," James explained, "do you know if there's something more efficient?"

"Errr," Yakir questioned, "there isn't really anything more efficient than a Hashtable. What exactly is the problem?"

"It's just too slow," James replied, "once I have real data in there, it takes almost five seconds to add, remove, or find, an item."

Yakir knew something was definitely wrong and sat with James to look at his code. Here's what he saw...

  class HashTable
  {
    public object[] keys;
    public object[] values;

    public HashTable()
    {
      keys = new object[0];
      values = new object[0];
    }

    public void Add(object key, object value)
    {
      Array.Resize(ref keys, keys.Length + 1);
      Array.Resize(ref values, values.Length + 1);
      keys[keys.Length - 1] = key;
      values[values.Length - 1] = value;
    }

    public void Remove(object key)
    {
      object[] tempKeys = new object[0];
      object[] tempValues = new object[0];
      for (int i = 0; i <= keys.Length - 1; i++)
      {
        if (!keys[i].Equals(key))
        {
          Array.Resize(ref tempKeys, tempKeys.Length + 1);
          Array.Resize(ref tempValues, tempValues.Length + 1);
          tempKeys[tempKeys.Length - 1] = keys[i];
          tempValues[tempValues.Length - 1] = values[i];
        }
      }
      keys = tempKeys;
      values = tempValues;
    }

    public object GetItem(object key)
    {
      for (int i = 0; i <= keys.Length - 1; i++)
      {
        if (keys[i].Equals(key))
        {
          return values[i];
        }
      }
      return null;
    }

    public int NumberOfItems
    {
      get
      {
        return keys.Length;
      }
    }
  }

"Uhhh," Yakir said, baffled. "Why didn't you use the built-in Hashtable class from System.Collections that I showed you?"

"I checked it out," James explained, "but it had too many functions, which means it's slow. My class only has 3 functions, so it's much more efficient."

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!