← Runtimes
Runtimes

Size, alignment, and padding

Why a record can take more bytes than its fields add up to.

Use field sizes and alignment rules to distinguish a native record’s footprint from its encoded bytes.

Outcome

Predict a record’s field offsets, size and array stride from its fields’ sizes and alignments, including nested records, and say which of those facts a language promises.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Alignment
The multiple of bytes a value’s address must be; a type with alignment 8 starts at an address divisible by 8.
Padding
Unused bytes a compiler inserts so the next field, or the next array element, is aligned.
Offset
Where a field starts, in bytes from the start of its record.
Stride
The byte distance between native array elements, equal to the element type’s size. An encoded format declares its own record stride.
DataView
A JavaScript built-in, usable from TypeScript, that reads and writes numbers at chosen byte offsets in an ArrayBuffer.

What a record’s size includes

A field’s offset is its byte distance from the start of a record. Alignment constrains where native values may start; padding fills gaps needed to satisfy those constraints. A record’s size can therefore exceed the sum of its field sizes, and its full size determines the distance between elements of a native array.

These facts belong to a particular representation and target. A serialized record instead follows a chosen byte schema. JavaScript does not expose an ordinary object’s native field layout; the TypeScript examples use DataView to specify encoded offsets explicitly. Measure or declare the representation before using its byte count.

01Measure

How many bytes does the record take?

The order service reserves room for a million events before passing a batch to its C reporting module. A status byte, timestamp and store number add up to eleven bytes, yet the native event occupies twenty-four on the recorded build. Work out the batch stride before changing its memory budget, then check what a nested shipment record contributes. The exported event log has its own explicit byte schema.

First reduce the batch to one event. Alignment constrains valid starting addresses for a native value. In the declared profile, the integer fields align to their widths; placing a wider field can leave a gap after a smaller one. The record also needs a stride that keeps every array element aligned. These are field-layout requirements, not measurements of an allocator’s total footprint.

Each native struct describes status, placed-at seconds and store. The TypeScript source instead encodes those values at chosen offsets in an eleven-byte DataView. Compare the encoded byte length with the native struct size; they answer different questions.

JavaScript exposes no C-style byte layout for an ordinary object. This source chooses an encoded schema with DataView; it measures the view’s byte length, not the runtime memory cost of a JavaScript object.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// TypeScript objects have no defined memory layout. An event log record is laid out
// by hand: each field is written at an offset the program chooses.

const record = new DataView(new ArrayBuffer(1 + 8 + 2));

record.setUint8(0, 1); // status code
record.setBigInt64(1, 1700000000n); // placed_at, Unix seconds
record.setUint16(9, 7); // store number

console.log(`bytes: ${record.byteLength}`);
console.log(`store read back: ${record.getUint16(9)}`);
How many encoded bytes does this DataView report?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --strict --target es2022 && node main.ts

The quoted observations come from the earlier ARM64 native/engine profiles, not a new measurement in this revision. Run each shown source to inspect your own compiler and target; Rust default layout can change between builds. The calculator separately fixes primitive sizes and alignments to 1, 2, 4 or 8. Other ABIs, annotations and 32-bit targets can differ.

02Order and stride

What changes when stricter alignment comes first?

With the declared-order native record understood, try a field order that fits the batch more tightly. In this simple profile, arranging fields by decreasing alignment avoids gaps between them; trailing padding can still remain. Native array elements are one sizeof apart. An encoded log uses whichever stride its schema defines.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// The same three fields, largest first. With DataView the offsets are chosen,
// so the order changes nothing about the size unless the program adds gaps.

const record = new DataView(new ArrayBuffer(8 + 2 + 1));

record.setBigInt64(0, 1700000000n); // placed_at, Unix seconds
record.setUint16(8, 7); // store number
record.setUint8(10, 1); // status code

console.log(`bytes: ${record.byteLength}`);
How many bytes does the reordered event take?

03Nested records

How does a record inside a record lay out?

The next event adds a shipment measurement as one field. Reusing its field-size sum would throw away the measurement record’s own padding. Under the calculator’s profile, the nested record contributes its full padded size and its largest field alignment. The outer placement must honor both; changing only the byte count or only the alignment can still move later fields incorrectly.

Declared layout profile: ShipmentEvent { carrier u16, weight Weight { kg f32, unit u8 }, fragile bool }
FieldSizeAlignOffset
Weight.kg440 (in Weight)
Weight.unit114 (in Weight)
ShipmentEvent.carrier22?
ShipmentEvent.weight???
ShipmentEvent.fragile11?
In the declared model, f32 is size/align 4 and u8/bool are size/align 1; u16 is size/align 2. Weight holds f32 then u8. ShipmentEvent holds u16, Weight, then bool. Where does Weight start, and how large is ShipmentEvent?

04Practice

Finish the layout calculator

The team turns its batch-layout assumptions into a calculator before extending the C interface with nested records. It reads declared fields and applies the stated C-like alignment profile. It does not discover a machine ABI or serialize a file; each level supplies the parts that already work.

The layout calculator

Size each field, lay out a record, then lay out records that contain records.

  1. easy · R-LAYOUT-V4-1 Size each field
  2. medium · R-LAYOUT-V4-2 Lay out a record
  3. hard · R-LAYOUT-V4-3 Lay out nested records
In the frontend Read an encoded event without borrowing a native struct layout. Optional

The browser receives one event as a Uint8Array view. Its schema fixes status at byte 0, placed-at seconds at byte 1, and store at byte 9, with an eleven-byte record and big-endian numbers. The view may be a window into a larger buffer. These components honor that window and display the fields; no native sizeof or JavaScript object layout is involved.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

export default function EventFields({ bytes }: { bytes: Uint8Array }) {
  if (bytes.byteLength !== 11) return <p>Expected an 11-byte event.</p>;

  const event = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);

  return (
    <dl>
      <dt>Status</dt>
      <dd>{event.getUint8(0)}</dd>
      <dt>Placed at (seconds)</dt>
      <dd>{event.getBigInt64(1, false).toString()}</dd>
      <dt>Store</dt>
      <dd>{event.getUint16(9, false)}</dd>
    </dl>
  );
}

DataView reads the timestamp at the unaligned schema offset 1. Its offsets are relative to this view, so byteOffset and byteLength preserve an incoming subarray window. The false arguments state this schema’s byte order. Eleven bytes describes the encoding, not a native ABI stride or the runtime cost of the displayed object.

Sources: ECMAScript: DataView objects,React: rendering component props,Svelte: derived state.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.