Bit shifting tricks and speeding up data structure
I'm pretty new to working directly with bits, but it is a lot of fun. I'm converting a javascript data structure to Flash.
So I'm thinking that Math.floor(uint/32) is the same as uint >> 5, right?
And that uint % 32 is the same as uint & 31 ? Evidently this works for modulos that are powers of 2, what a cool trick.
Using both of those cut the time needed for storing and retrieving data about in half.
But it is still takes about three times longer that just using the native Object. This is in reference to my previous post http://forums.adobe.com/message/5001353#5001353 but that didn't get very far.
So if anybody has any suggestions on how else to speed this up it would be very helpful:
package {
public class BloomFilter {
private var _m:uint;
private var _k:int;
private var _locations:Vector.<uint>;
public var _buckets:Vector.<uint>;
public function BloomFilter(m:uint,k:int) {
_m=m;
_k=k;
_locations=new Vector.<uint> ;
_buckets=new Vector.<uint> ;
var n:uint=Math.ceil(m/32);
var i:int=-1;
while (++i<n) {
_buckets=0;
}
}
private function hash(v:String) {
var i:int=-1;
var X:uint;
var a,b:uint;
a=fnv_1a(v);
b=fnv_1a_b(a);
X=a%_m;
while (++i<_k) {
_locations=X<0? (X+_m) : X;
X=(X+b)%_m;
}
}
public function add(v:String) {
hash(v);
var i:int=-1;
while (++i<_k) {
_buckets[_locations>>5]|=1<<(_locations&31);
}
}
public function test(v:String):Boolean {
hash(v);
var i:int=-1;
var b:uint;
while (++i<_k) {
b=_locations;
if ((_buckets[b>>5] & (1 << (b&31))) === 0) {
return false;
}
}
return true;
}
// Fowler-Noll-Vo hash
private function fnv_1a(v:String):uint {
var n:int=v.length;
var a:uint=2166136261;
var c,d:uint;
var i:int=-1;
while (++i<n) {
c=v.charCodeAt(i);
if (d=c&0xff000000) {
a^=d>>24;
a+=(a<<1) + (a<<4) + (a<<7) + (a<<8)+ (a<<24);
}
if (d=c&0xff0000) {
a^=d>>16;
a+=(a<<1) + (a<<4) + (a<<7) + (a<<8)+ (a<<24);
}
if (d=c&0xff00) {
a^=d>>8;
a+=(a<<1) + (a<<4) + (a<<7) + (a<<8)+ (a<<24);
}
a^=c&0xff;
a+=(a<<1) + (a<<4) + (a<<7) + (a<<8)+ (a<<24);
}
a+=a<<13;
a^=a>>7;
a+=a<<3;
a^=a>>17;
a+=a<<5;
return a&0xffffffff;
}
// One additional iteration of FNV
private function fnv_1a_b(a:uint):uint {
a+=(a<<1) + (a<<4) + (a<<7) + (a<<8)+ (a<<24);
a+=a<<13;
a^=a>>7;
a+=a<<3;
a^=a>>17;
a+=a<<5;
return a&0xffffffff;
}
}
}
