code_junkie

Size of a byte in memory - Java

Nov 11th, 2011
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. class LotsOfBytes
  2. {
  3. byte a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
  4. byte b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;
  5. byte c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;
  6. byte d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;
  7. byte e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;
  8. }
  9.  
  10. class LotsOfInts
  11. {
  12. int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
  13. int b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;
  14. int c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;
  15. int d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;
  16. int e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;
  17. }
  18.  
  19.  
  20. public class Test
  21. {
  22. private static final int SIZE = 1000000;
  23.  
  24. public static void main(String[] args) throws Exception
  25. {
  26. LotsOfBytes[] first = new LotsOfBytes[SIZE];
  27. LotsOfInts[] second = new LotsOfInts[SIZE];
  28.  
  29. System.gc();
  30. long startMem = getMemory();
  31.  
  32. for (int i=0; i < SIZE; i++)
  33. {
  34. first[i] = new LotsOfBytes();
  35. }
  36.  
  37. System.gc();
  38. long endMem = getMemory();
  39.  
  40. System.out.println ("Size for LotsOfBytes: " + (endMem-startMem));
  41. System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE)));
  42.  
  43. System.gc();
  44. startMem = getMemory();
  45. for (int i=0; i < SIZE; i++)
  46. {
  47. second[i] = new LotsOfInts();
  48. }
  49. System.gc();
  50. endMem = getMemory();
  51.  
  52. System.out.println ("Size for LotsOfInts: " + (endMem-startMem));
  53. System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE)));
  54.  
  55. // Make sure nothing gets collected
  56. long total = 0;
  57. for (int i=0; i < SIZE; i++)
  58. {
  59. total += first[i].a0 + second[i].a0;
  60. }
  61. System.out.println(total);
  62. }
  63.  
  64. private static long getMemory()
  65. {
  66. Runtime runtime = Runtime.getRuntime();
  67. return runtime.totalMemory() - runtime.freeMemory();
  68. }
  69. }
  70.  
  71. Size for LotsOfBytes: 88811688
  72. Average size: 88.811688
  73. Size for LotsOfInts: 327076360
  74. Average size: 327.07636
  75. 0
Add Comment
Please, Sign In to add comment