JUnion為 Java 提供結(jié)構(gòu)類型
JUnion 用于為 Java 編程語(yǔ)言提供結(jié)構(gòu)類型。
功能特性
-
結(jié)構(gòu)類型
-
自動(dòng)對(duì)齊數(shù)據(jù)
-
手動(dòng)對(duì)齊數(shù)據(jù)
-
創(chuàng)建結(jié)構(gòu)類型的數(shù)組
-
64 位可尋址數(shù)組
-
修改原生 DirectByteBuffers
-
檢查數(shù)組下標(biāo)
-
嵌套結(jié)構(gòu)
-
結(jié)構(gòu)引用
-
空引用檢查
-
數(shù)組切割
-
泛型
-
棧分配
查看更多特性介紹 https://tehleo.github.io/junion/features.html
當(dāng)創(chuàng)建 int 數(shù)組時(shí),我們有兩個(gè)主要選項(xiàng):
int[] intArray = new int[1000]; Integer[] intBoxedArray = new Integer[1000];
那么,intArray, intBoxedArray 需要多少個(gè)字節(jié)才能存儲(chǔ) 1000 個(gè) int 數(shù)據(jù)?結(jié)果如下 ——
intArray 4016 bytes 4*1000 + ~16(around 16 bytes for array header)
intBoxedArray 20016 bytes (4 + ~12 + ~4)*1000 + ~16 (具體數(shù)據(jù)取決于 VM)
可以看到,后者幾乎是前者的 5 倍,因此我們應(yīng)該偏向于選擇使用原始數(shù)組 (primitive arrays)。
考慮這樣一個(gè)問(wèn)題
class Point { float x,y;}
Point[] arr = new Point[500];
arr 占用了 14016 個(gè)字節(jié),而數(shù)據(jù)包含了 500 個(gè) points,每個(gè) points 有兩個(gè)浮點(diǎn)數(shù),因此 4000 個(gè)字節(jié)應(yīng)該足夠了。
但如果 Point 是一個(gè)結(jié)構(gòu)類型(struct),arr 大約只占用 4000 個(gè)字節(jié)。
使用 JUnion,可以通過(guò) @Struct 注解標(biāo)記一個(gè)類來(lái)做到這一點(diǎn)!
創(chuàng)建 struct Vec3:
@Struct
public class Vec3 {
public float x,y,z;
}
然后,你可以將其用作:
//Create a new struct array Vec3[] arr = Vec3[10]; arr[5].x = 10; Vec3 v = arr[5]; ... // ByteBuffer a = ByteBuffer.allocateDirect(10*Mem.sizeOf(Vec3.class)) .order(ByteOrder.nativeOrder()); //Modify Direct Native Bytebuffer as it were a struct Vec3 arr = Mem.wrap(a); arr[5].x = 10; ...
性能測(cè)試
