Sub topic 6
Zero-copy sharing and who owns the memory
This chapter assumes you know basic Python and NumPy, and that you have read the previous chapters on buffers, validity bitmaps, arrays and tables. Here you will learn what "zero-copy" means in Arrow, which conversions qualify, and how Arrow decides when memory can be freed.
What zero-copy means
A zero-copy operation gives you a new object that points at the same bytes as the original. No values are duplicated, so the cost does not grow with the data size. Converting a 10 GB array and a 10-element array takes about the same time.
Arrow makes this possible because its layout is fixed. A 64-bit integer column with no nulls is a contiguous run of 8-byte values, which is the same thing NumPy stores for an int64 array. Both libraries can read the same memory without translating it.
Zero-copy is not guaranteed. It works only when the source layout matches what the target expects, as the table later in this chapter shows.
Buffers are reference-counted views
An Arrow array does not own raw bytes directly. It holds references to Buffer objects, and each buffer is a pointer, a length, and a reference to whatever keeps the memory alive. That owner can be Arrow's memory pool, a NumPy array, a Python bytearray, or a memory-mapped file.
The owner stays alive as long as any object references it. This is how sharing stays safe: a buffer holds its owner, and an array holds its buffers.
The next example builds an Arrow array from NumPy, converts it back, and checks that all three objects use the same address.
import numpy as np
import pyarrow as pa
values = np.array([1, 2, 3], dtype=np.int64)
arr = pa.array(values)
back = arr.to_numpy(zero_copy_only=True)
print(back)
print(back.ctypes.data == arr.buffers()[1].address)
print(back.flags.writeable)The address comparison prints True, which confirms that no copy happened. The last line prints False. Arrow data is treated as immutable, so the NumPy view is read-only.
When a conversion copies
Arrow's to_numpy has a zero_copy_only flag. With zero_copy_only=True, Arrow raises an error instead of copying silently. Use it in code where a hidden copy would be a bug.
import pyarrow as pa
arr = pa.array([1, None, 3], type=pa.int64())
try:
arr.to_numpy(zero_copy_only=True)
except pa.ArrowInvalid:
print("copy needed")The nulls are the reason. NumPy's int64 has no way to mark a missing value, so Arrow would have to produce a float array with NaN or a masked array. Either one is a new allocation.
| Source | Zero-copy to NumPy? | Reason |
|---|---|---|
| Integer or float array, no nulls, one chunk | Yes | Same contiguous values layout |
| Same array with nulls | No | The validity bitmap has no NumPy equivalent |
| Boolean array | No | Arrow packs booleans as bits, NumPy uses one byte each |
| String or binary array | No | Arrow uses offsets plus one data buffer, NumPy uses Python objects |
| Chunked array with several chunks | No | Chunks must be joined into one contiguous block |
With pandas the picture is similar. Table.to_pandas() often copies, because pandas groups columns of the same type into 2-D blocks. You can reduce this with to_pandas(split_blocks=True), which keeps columns separate, and with zero_copy_only=True, which makes any required copy an error. Columns with nulls, strings and timestamps still need conversion.
Slices share buffers
Slicing an Arrow array is zero-copy as well. A slice is a new array object with the same buffers and a different offset and length.
import pyarrow as pa
arr = pa.array(range(1_000_000), type=pa.int64())
view = arr.slice(10, 5)
print(view.offset, len(view))
print(arr.buffers()[1].address == view.buffers()[1].address)
print(view.to_pylist())The output is 10 5, then True, then [10, 11, 12, 13, 14]. The slice reports the full buffer's address because buffers are not cut up. The offset is applied when values are read.
This has a consequence for memory. A slice of 5 values keeps all 8 MB alive. Slicing is cheap, but it does not free anything.
Ownership and lifetime
The memory pool tracks allocations that Arrow makes itself. The next example shows that a small slice keeps the parent's buffer alive, and that the memory returns only when the last reference is gone.
import pyarrow as pa
pool = pa.default_memory_pool()
before = pool.bytes_allocated()
big = pa.array(range(1_000_000), type=pa.int64())
small = big.slice(0, 3)
del big
print(pool.bytes_allocated() - before > 7_000_000)
del small
print(pool.bytes_allocated() - before < 1_000)Both lines print True. After del big, the 8 MB are still allocated because small references them. After del small, the pool returns to its starting level.
If you need to keep a small piece of a large array, make a real copy so the large buffer can be released. A common way is pa.concat_arrays([small]). For a table, table.combine_chunks() does the same job per column.
Buffers from outside Arrow
Arrow can wrap memory it did not allocate. In that case the Arrow buffer holds a reference to the foreign owner, and that owner must stay valid for as long as Arrow uses it.
import pyarrow as pa
data = bytearray(b"\x01\x00\x00\x00\x02\x00\x00\x00")
buf = pa.py_buffer(data)
arr = pa.Array.from_buffers(pa.int32(), 2, [None, buf])
print(arr.to_pylist())
data[0] = 9
print(arr.to_pylist())The first line prints [1, 2] and the second [9, 2]. The array did not copy the bytes. It reads whatever the bytearray contains, which here assumes a little-endian machine, as nearly all current ones are. Python also protects the memory: while the buffer exists, calling data.append(0) raises BufferError, because resizing could move the bytes and leave Arrow with a dangling pointer.
The mutation hazard
Zero-copy sharing means that a change through one handle shows up in every other handle. The previous example demonstrated this on purpose. In real programs it appears by accident:
- You build an Arrow array from a NumPy array and later modify the NumPy array in place. The Arrow array changes too.
- Arrow marks its own buffers as immutable, so Arrow-owned data is safe. Foreign owners such as NumPy and
bytearrayare not. - A NumPy view obtained from Arrow is read-only. Setting
flags.writeable = Truecan fail or hide a bug, and you should copy instead withnp.array(arr)orarr.to_numpy().copy().
Memory-mapped and borrowed memory
The owner does not have to be RAM that Arrow allocated. A memory-mapped file can also own a buffer, and the next chapters build on this. The rule stays the same. The buffer keeps its owner alive, so the mapping stays open while any array references it.
Across languages and processes the idea becomes the C data interface. There, a release callback lets the consumer tell the producer when it has finished with the memory. The mechanics differ, but the principle is identical: whoever lends memory must know when the borrower is done.
Summary of rules
- A buffer is a pointer, a length and an owner reference. The owner lives as long as any buffer uses it.
- Slices,
to_numpyon null-free primitive arrays, andpa.arrayon NumPy primitives share memory. - Nulls, booleans, strings and multi-chunk data force a copy to NumPy.
- A small slice keeps its whole parent buffer alive until you copy it.
- Arrow's own buffers are immutable. Foreign memory that you wrap can still change under Arrow.
Exercise
You run pa.array([1.0, 2.0, 3.0]).to_numpy(zero_copy_only=True) and it succeeds. You then change the array to pa.array([1.0, None, 3.0]) and the same call raises ArrowInvalid. Why? Separately, you slice 10 rows from a 100 million row array, delete the original and see memory use barely drop. Why?
Show answer
The first array has no nulls, so its values buffer matches NumPy's float64 layout and can be shared. With a null, the validity bitmap marks a missing value that float64 in NumPy cannot represent, so Arrow would have to build a new array (for example with NaN), which is a copy. The memory stays high because a slice is a view with an offset and length over the same buffers. It holds a reference to the whole 100 million row buffer, so the buffer is freed only when the slice is gone or replaced by a real copy, such as with pa.concat_arrays.