You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

null与空ArrayList<String>哪个占用内存空间更多?

null vs. Empty ArrayList<String>: Memory Comparison

Great question—this is a common point of confusion when reasoning about Java memory usage, so let’s break it down clearly:

First: What’s the memory cost of null?

In Java, null is a value that a reference variable can hold to indicate it doesn’t point to any object. The size of this reference depends on your JVM and system architecture:

  • On 32-bit JVMs: 4 bytes per reference
  • On 64-bit JVMs: 8 bytes by default, or 4 bytes if compressed pointers (enabled by default in most modern JVMs for heaps under 32GB) are turned on.

Crucially: null doesn’t allocate any object memory—it’s just a marker value in the reference variable itself.

Next: Memory cost of an empty ArrayList<String>

An empty ArrayList is a full Java object, with its own memory footprint. Let’s break down what makes up its size (using HotSpot JVM as an example, since it’s the most common):

  1. Object Header: Every Java object has a header containing metadata (Mark Word for locking/hashing, Klass Pointer to the class definition).

    • With compressed pointers (64-bit): 12 bytes
    • Without compressed pointers (64-bit): 16 bytes
    • 32-bit JVM: 8 bytes
  2. Instance Variables: ArrayList has three core instance variables:

    • elementData: A reference to the underlying array (holds the list elements). For an empty ArrayList, this points to a shared static empty array (EMPTY_ELEMENTDATA), so we don’t count the array’s memory here (it’s reused across all empty instances).
    • size: An int (4 bytes) tracking the number of elements (0 for empty).
    • modCount: An int (4 bytes) for fail-fast iterator checks.
  3. Memory Alignment: Java objects are padded to the nearest multiple of 8 bytes to optimize memory access.

Putting this together for common scenarios:

  • 64-bit with compressed pointers: 12 (header) + 4 (elementData) + 4 (size) + 4 (modCount) = 24 bytes (already aligned to 8)
  • 64-bit without compressed pointers: 16 (header) + 8 (elementData) + 4 + 4 = 32 bytes (aligned)
  • 32-bit JVM: 8 (header) +4+4+4=20 → padded to 24 bytes

The Bottom Line

  • A null reference only uses the size of the reference variable (4 or 8 bytes) and no additional object memory.
  • An empty ArrayList<String> uses that same reference size (for the variable pointing to it) plus 24–32 bytes for the ArrayList object itself.

So the empty ArrayList takes significantly more memory than a null reference.

内容的提问来源于stack exchange,提问作者jpganz18

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:22:24