利用hasOwnProperty实现的高效的javascript hashtable
javascript中,object的实现就是hash表,因此只要在object上封装点方法,再利用原生的hasOwnProperty方法就可以实现简单高效的hashtable
测试如下:
Code
得出的结果是,100000大的hash表,进行1000次的判断,才花费15ms. 很快的速度了,可以用来做程序的优化.
注意: 字符串和数字相加会有糟糕的效率,导致时间多花了一倍,影响测试.
var HashTable = Class.create();
HashTable.prototype=
{
initialize:function()
{
this._content ={};
},
Count:function()
{
var count = 0;
for(var i in this._content) count++;
return count;
},
Items:function(key)
{
if(this.Contains(key))
{
return this._content[key];
}
},
Add:function(key,value)
{
if(this._content.hasOwnProperty(key))
{
return false;
}
else
{
this._content[key] = value;
return true;
}
},
Clear:function()
{
this._content = {};
},
Contains:function(key)
{
return this._content.hasOwnProperty(key);
},
Remove:function(key)
{
delete this._content[key];
}
}
HashTable.prototype=
{
initialize:function()
{
this._content ={};
},
Count:function()
{
var count = 0;
for(var i in this._content) count++;
return count;
},
Items:function(key)
{
if(this.Contains(key))
{
return this._content[key];
}
},
Add:function(key,value)
{
if(this._content.hasOwnProperty(key))
{
return false;
}
else
{
this._content[key] = value;
return true;
}
},
Clear:function()
{
this._content = {};
},
Contains:function(key)
{
return this._content.hasOwnProperty(key);
},
Remove:function(key)
{
delete this._content[key];
}
}
测试如下:
得出的结果是,100000大的hash表,进行1000次的判断,才花费15ms. 很快的速度了,可以用来做程序的优化.
注意: 字符串和数字相加会有糟糕的效率,导致时间多花了一倍,影响测试.
