想象一下,我有兩個byte []數組,b1和b2,它們的字節對應兩個雙精度。 一個選擇會是這樣的......比較存儲在字節數組中的雙精度的最有效方法?
double thisValue = readDouble(b1, s1);
double thatValue = readDouble(b2, s2);
return (thisValue < thatValue ? -1 : (thisValue == thatValue ? 0 : 1));
它採用...
/** Parse an integer from a byte array. */
public static int readInt(byte[] bytes, int start) {
return (((bytes[start ] & 0xff) << 24) +
((bytes[start+1] & 0xff) << 16) +
((bytes[start+2] & 0xff) << 8) +
((bytes[start+3] & 0xff)));
}
/** Parse a long from a byte array. */
public static long readLong(byte[] bytes, int start) {
return ((long)(readInt(bytes, start)) << 32) +
(readInt(bytes, start+4) & 0xFFFFFFFFL);
}
/** Parse a double from a byte array. */
public static double readDouble(byte[] bytes, int start) {
return Double.longBitsToDouble(readLong(bytes, start));
}
(Apache的Hadoop的源here和here採取代碼)。
事情是,你有他們的字節表示,所以看起來很浪費,實際上他們成爲一個雙重的,但也許這是大大優化,以至於可以忽略不計。我確信Hadoop的人們知道他們在做什麼,我只是好奇爲什麼直接比較這些比特不會更好/更快?或者,也許編譯器足夠聰明,可以看到這類事情並做到這一點。
由於