Java 中 byte/Integer 数组的实际数据大小是多少

Whats is the actual data size of an byte/Integer array in Java

我的问题是一个非常基础的问题,但我仍然很难完全理解它:

我的任务是发送一个包含 512 字节随机数据的 UDP 数据包 (Java)。所以这等于 4096 位。如果我发送一个大小为 4096 的字节数组(填充为“0”),是否等于 512 字节?

非常感谢:)

我在这里发现了一篇有趣的文章:dzone.com

以下是重要部分:

How to calculate memory usage of a Java object?: Very simplified explanation of how one could calculate a memory of any Java object. For example, lets say, you want to calculate the memory of a Java object which holds two int variables, one boolean variable, one Long object, and a reference to other objects. The memory would turn out to be following:

  • 8 bytes for the object header

  • 2 x 4 = 8 bytes for two int variables

  • 1 byte for a boolean variable

  • 8 bytes (object reference) + 8 bytes for long data type = 16 bytes for long object

  • 4 bytes for reference to some other object

The total size of the above mentioned object will be 8 + 8 + 1 + 16 + 4 = 37 bytes + 3 bytes (for padding) = 40 bytes.

How to calculate memory usage of a Java array?: The page presents examples on how to calculate size of a Java array object.

For example, lets say a Java array consisting of 20 Integer objects. Following is the detail on the size: 12 bytes for array header object (8 bytes for header and 4 bytes for storing length of the array) ==> 20 x 16 bytes = 320 bytes for integer objects.