Deep Dive • 20 August 2026 • Written by Lochan Chugh
isTriviallyIdentical: Fast O(1) Identity Audits in Swift
isTriviallyIdentical: Fast O(1) Identity Audits in Swift
When comparing large data structures, dictionaries, or sets for equality using the == operator, the Swift runtime recursively checks every element. In layout engines or performance-critical loops (like diffing lists in SwiftUI or collection changes in database updates), running these recursive evaluations on every pass can impact performance.
Swift 6.4 introduces isTriviallyIdentical(to:) via SE-0494. This method provides a constant-time, $O(1)$ check to verify if two instances share the exact same underlying storage or memory location. It allows you to skip deep, expensive semantic equality checks when objects are identical.
Bypassing Deep Comparisons in Custom Collection Diffing
You can use isTriviallyIdentical to optimize custom diffing routines by adding a fast-path check.
If two collections share the same storage (common in copy-on-write types like String, Array, or Dictionary before they are mutated), the check returns true immediately without inspecting any elements:
import Foundation
struct LogBatch: Equatable {
let id: UUID
let entries: [String]
static func == (lhs: LogBatch, rhs: LogBatch) -> Bool {
// 1. Check if the batch metadata matches
guard lhs.id == rhs.id else { return false }
// 2. Performance Fast Path: Check if the underlying array storage is identical
// Developer Thoughts: isTriviallyIdentical() is an O(1) pointer comparison.
// If the arrays share the same memory reference, we avoid an O(N) element comparison loop.
if lhs.entries.isTriviallyIdentical(to: rhs.entries) {
return true
}
// 3. Fallback: Perform the full element-by-element check
return lhs.entries == rhs.entries
}
}
Behavior Axioms & Constraints
- Reflexivity:
a.isTriviallyIdentical(to: a)is guaranteed to betrue. - Implication: If
a.isTriviallyIdentical(to: b)istrue, thena == bis guaranteed to betrue. - The Reverse is False: If two collections contain identical elements but reside in different memory allocations,
isTriviallyIdenticalreturnsfalse, falling back to standard==evaluation.
Summary
isTriviallyIdentical(to:) is a valuable performance tool for authors of collections, layout frameworks, and diffing libraries. By performing a quick pointer comparison, it eliminates unnecessary traversal of unchanged data structures. Use it as an early optimization check before executing heavy, recursive equality checks.