Hashtable vs. Set

Benchmark created by Kit Goncharov on


Preparation HTML

<script src="http://jshashtable.googlecode.com/svn/trunk/hashtable.js"></script>
<script>
  // @getify's solution
  var Set = (function() {
   var indexOf = Array.prototype.indexOf;
  
   if (typeof indexOf !== 'function') {
    indexOf = function(value) {
     for (var index = 0, length = this.length; index < length; index++) {
      if (this[index] === value) {
       return index;
      }
     }
     return -1;
    };
   }
  
   function Set() {
    this.set = [];
   }
  
   Set.prototype = {
    'constructor': Set,
    'put': function(key, value) {
     var index = indexOf.call(this.set, key);
     if (index !== -1 && index % 2 === 0) {
      this.set.splice(index, 2);
     }
     this.set.push(key, value);
    },
    'get': function(key) {
     var index = indexOf.call(this.set, key);
     return (index !== -1 && index % 2 === 0) ? this.set[++index] : null;
    },
    'containsKey': function(key) {
     var index = indexOf.call(this.set, key);
     return (index !== -1 && index % 2 === 0);
    },
    'containsValue': function(value) {
     var index = indexOf.call(this.set, value);
     return (index !== -1 && index % 2 !== 0);
    },
    'remove': function(key) {
     var index = indexOf.call(this.set, key),
         value = null;
     if (index !== -1 && index % 2 === 0) {
      value = this.set.splice(index, 2)[1];
     }
     return value;
    }
   };
  
   return Set;
  }());
  
  var hash = new Hashtable(),
      set = new Set();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Hashtable Operations
var first = {},
    second = {};

hash.put(first, "First Value");
hash.put(second, "Second Value");

hash.containsKey(first);
hash.containsKey(second);

hash.containsValue("First Value");
hash.containsValue("Second Value");

hash.get(first);
hash.get(second);

hash.remove(first);
hash.remove(second);
ready
Set Operations
var first = {},
    second = {};

set.put(first, "First Value");
set.put(second, "Second Value");

set.containsKey(first);
set.containsKey(second);

set.containsValue("First Value");
set.containsValue("Second Value");

set.get(first);
set.get(second);

set.remove(first);
set.remove(second);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Kit Goncharov on