java中用byte[]數組實現的隊列和用Byte[]實現的隊列實際占用空間對比


我用byte[]實現了一個隊列,創建對象,也用ArrayBlockingQueue<Byte>創建對象,添加10M個byte/Byte后通過對象流輸出到文件,文件的大小可以代表對象的大小,一探java裝箱額外占用空間的大小。

測試代碼:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Queue;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;

import com.idealisan.structure.ArrayBlockingByteValueQueue;

public class TestMen {
    static int capacity = 1024 * 1024 * 10;

    public static void main(String[] args) {
        ArrayBlockingQueue<Byte> pointerQueue = new ArrayBlockingQueue<Byte>(capacity);
        ArrayBlockingByteValueQueue valueQueue = new ArrayBlockingByteValueQueue(capacity);

        fillQueue(valueQueue);
        FileOutputStream os;
        try {
            os = new FileOutputStream(new File("F:/ttt/value10.dat"));

            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(valueQueue);
            oos.flush();
            oos.close();
            os.flush();
            os.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        valueQueue = null;

        
        fillQueue(pointerQueue);
        try {
            os = new FileOutputStream(new File("F:/ttt/pointer10.dat"));
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(pointerQueue);
            oos.flush();
            oos.close();
            os.flush();
            os.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        pointerQueue = null;

    }

    private static void fillQueue(Queue<Byte> queue) {
        while (queue.size() < capacity) {
            queue.offer(new Byte((byte) 1));
        }
    }
}

最后的結果是裝箱的Byte多使用了600%的空間,當然,一般不會有10M個對象那么多,也很少會讓每個字節成為一個單獨的對象,太浪費空間了。其中值類型的byte也額外使用了大約1kB的空間,應該是用於存放容器對象的信息。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM