快速比较字节格式的long? [英] Fast(er) comparison of longs in byte format?

查看:91
本文介绍了快速比较字节格式的long?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有byte []键的键值存储。其中一些键将用于long(long本身,也包括Localdate和LocalTime实例)。

I have a key value store that has byte[] keys. Some of these keys will be used for longs (longs themselves, also Localdate and LocalTime instances).

我有一个不错的比较器,使用标准Java和Guava:

I have a nice clean comparator, using standard Java and Guava:

    @Override
    public int compare(byte[] left, byte[] right) {
        long leftLong = Longs.fromByteArray(left);
        long rightLong = Longs.fromByteArray(right);
        return Long.compare(leftLong, rightLong);
    }

,但是速度比我预期的要慢。对100,000个long进行排序需要100毫秒,而对100,000个int进行排序则需要6毫秒。

but it's slower than I would expect. Sorting 100,000 longs takes 100ms, whereas sorting 100,000 ints takes 6ms.

是否可以通过避免int转换来比较两个long的更快方法?

Is there a faster way to compare two longs, perhaps by avoiding the int conversion?

(您可能想知道它是否真的需要更快。如果可能的话,因为每次搜索,扫描,插入和删除long都会调用它,日期等。)

(You may be wondering if it really needs to be faster. If possible yes, as it will be called for every search, scan, insert, and delete of longs, dates, etc. into the store.)

推荐答案

我并不感到惊讶,它花了很长时间:分配和销毁一万亿个订单小物件似乎很费力。为什么不只比较数组本身呢?

I am not surprised it takes long: allocating and destroying an order of a trillion small objects seems taxing. Why not just compare arrays themselves?

public int compare(byte[] left, byte[] right) {
    int cmp = 0;
    for(int i = 0; i < 8 && cmp == 0; i++) { 
       cmp = (i == 0 || (left[i] >= 0 == right[i] >= 0)) ? left[i] - right[i] : right[i] - left[i]           
    }
    return cmp;
}

这篇关于快速比较字节格式的long?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆