RoaringBitmap 源码

当调用add方法时,先把x分成高16位和低16位。
">>> "是 Java 中的无符号右移操作符,表示将 x 的二进制表示向右移动 16 位
当x为 65535 ,二进制为1111111111111111,16个1,即丢掉右16位,左边补0,所以x >>> 16=0,
当x为 65536 ,二进制为10000000000000000,17位,右16个0,所以x >>> 16=1

    public void add(int x) {
        char hb = Util.highbits(x);
        int i = this.highLowContainer.getIndex(hb);
        if (i >= 0) {
            this.highLowContainer.setContainerAtIndex(i, this.highLowContainer.getContainerAtIndex(i).add(Util.lowbits(x)));
        } else {
            ArrayContainer newac = new ArrayContainer();
            this.highLowContainer.insertNewKeyValueAt(-i - 1, hb, newac.add(Util.lowbits(x)));
        }

    }

 protected static char highbits(int x) {
        return (char)(x >>> 16);
    }
默认初始化4个容器(桶),key都为0,数字65535 高16位为0,放在0号桶中,65536高16位为1,放在1号桶中,同一个桶中顺序排列,如果新插入的数据不是桶中最大的,数组需要copy进行插入,如果是最大的,直接放到最后面的位置,如果桶中的数据容量大于4096,则转换成toBitmapContainer容器存储。
 public Container add(char x) {
        if (this.cardinality == 0 || this.cardinality > 0 && x > this.content[this.cardinality - 1]) {
            if (this.cardinality >= 4096) {
                return this.toBitmapContainer().add(x);
            }

            if (this.cardinality >= this.content.length) {
                this.increaseCapacity();
            }

            this.content[this.cardinality++] = x;
        } else {
            int loc = Util.unsignedBinarySearch(this.content, 0, this.cardinality, x);
            if (loc < 0) {
                if (this.cardinality >= 4096) {
                    return this.toBitmapContainer().add(x);
                }

                if (this.cardinality >= this.content.length) {
                    this.increaseCapacity();
                }

                System.arraycopy(this.content, -loc - 1, this.content, -loc, this.cardinality + loc + 1);
                this.content[-loc - 1] = x;
                ++this.cardinality;
            }
        }

        return this;
    }

在这里插入图片描述
65535在0号桶,存的低16位,就是本身65535
65536在1号桶,存的低16位,16个0,即0
在这里插入图片描述
访问的时候,也是先计算高位获得桶,然后用低位来算是否包含

    public boolean contains(int x) {
        char hb = Util.highbits(x);
        Container c = this.highLowContainer.getContainer(hb);
        return c != null && c.contains(Util.lowbits(x));
    }

存储1亿的随机数,预计占用12571312字节≈12M的内存空间
在这里插入图片描述

总共1526个BitmapContainer ,每个BitmapContainer 都是固定长度8192字节=8k.
在这里插入图片描述

下面是gpt的分析,跟上面的结果是大概率匹配的

  • 1.如果用BitmapContainer 存储1亿个随机数
    在这里插入图片描述

  • 2.如果用ArrayContainer 存储1亿个随机数
    在这里插入图片描述

参考:

https://blog.csdn.net/S_ZaiJiangHu/article/details/125656217

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值