Swift & Objective-C

Swift MemoryLayout:size・stride・alignmentを実測する

フィールド順を変えた構造体、Optional、existentialのサイズを測定し、観察値を恒久的なABI保証やヒープ全体の使用量と区別します。

読了 3 分
Swift MemoryLayout:size・stride・alignmentを実測するのカバー画像

配列要素の間隔を比較するならsizeだけでなくstrideも確認します。sizeは値の占有範囲で、strideは次の値までのアラインメント込みの間隔です。プロパティ順でパディングが変わり、両者が変化することがあります。

仕組みと設計の判断基準

BadはBool、Double、Int32、GoodはDouble、Int32、Boolの順です。この対象ではDoubleのalignmentが8なので、小さいフィールドの後にはパディングが生じます。サイズはコンパイラー、対象、型定義ごとに確認し、宣言順を永久的なABI契約と見なさないでください。 一次資料

再現コード

二つの構造体のsize・stride・alignmentに加え、Bool?、Int?、クラス制約のない単一プロトコルexistential、Array値のサイズを測ります。64ビットを前提とし、記録した期待値と違えば停止して環境差を知らせます。

この独立したサンプルは2026-10-23に、arm64 macOS向けのApple Swift 6.4をSwift 6言語モードで実行しました。ネットワーク接続や追加パッケージは不要です。

Swiftファイル全体をダウンロード

ダウンロード先のフォルダーで実行してください。検証条件を満たさない場合はpreconditionで停止します。検証が削除されるため、-Ouncheckedは使用しないでください。

swift -swift-version 6 swift-memory-layout-size-stride-alignment.swift
struct Bad {
    var flag: Bool
    var value: Double
    var count: Int32
}
struct Good {
    var value: Double
    var count: Int32
    var flag: Bool
}
protocol Shape {}

precondition(MemoryLayout<Int>.size == 8, "This experiment requires a 64-bit target")
let bad = (MemoryLayout<Bad>.size, MemoryLayout<Bad>.stride, MemoryLayout<Bad>.alignment)
let good = (MemoryLayout<Good>.size, MemoryLayout<Good>.stride, MemoryLayout<Good>.alignment)
print("bad=size:\(bad.0),stride:\(bad.1),alignment:\(bad.2)")
print("good=size:\(good.0),stride:\(good.1),alignment:\(good.2)")
print("optional=bool-size:\(MemoryLayout<Bool?>.size),int-size:\(MemoryLayout<Int?>.size),int-stride:\(MemoryLayout<Int?>.stride)")
print("existential=\(MemoryLayout<any Shape>.size) array-value=\(MemoryLayout<[Int]>.size)")
precondition(bad == (20, 24, 8) && good == (13, 16, 8), "Layout differs from the recorded toolchain")
precondition(MemoryLayout<Bool?>.size == 1 && MemoryLayout<Int?>.size == 9)
precondition(MemoryLayout<Int?>.stride == 16 && MemoryLayout<any Shape>.size == 40)
precondition(MemoryLayout<[Int]>.size == 8)

実行結果と読み取り方

bad=size:20,stride:24,alignment:8
good=size:13,stride:16,alignment:8
optional=bool-size:1,int-size:9,int-stride:16
existential=40 array-value=8

今回Badはsize 20・stride 24、Goodはsize 13・stride 16でした。連続する100万要素ではstrideだけで8,000,000バイトの差です。Bool?のsizeは1、Int?はsize 9・stride 16、any Shapeは40、Array値自体は8バイトでした。

適用範囲と注意点

Array値が8バイトでも全要素がそこに入るわけではありません。ヒープ上の保存領域やアロケーターの負担は測定外です。existentialの40バイトも全any型に共通しません。記録した対象での観察値であり、他環境の保証ではありません。

次に確認すること

まずインスタンス数とヒープ割り当てを測ります。大きなコレクションでパディングが問題になる場合に限り、API互換性も考慮して並び替えを検討します。値と参照が曖昧ならclassとstructの実験から確認してください。

関連する実験

出典と確認基準

  • Swift ABI: Type LayoutSwift.org · 公式ドキュメント · 確認日 2026年10月23日根拠: 実装の契約と説明の根拠です。出力は、この記事に掲載した実験で別途確認しました。