apple / swift-collections

Commonly used data structures for Swift
Apache License 2.0
3.55k stars 270 forks source link

[OrderedSet] forward ordered set equality to elements property #340

Closed vanvoorden closed 5 months ago

vanvoorden commented 5 months ago

Background

https://github.com/apple/swift-collections/pull/335

Similar to OrderedDictionary, we can forward our OrderedSet equality checks down to the ContiguousArray instance to take advantage of early return when both arrays point to the same identity (no need to perform a linear comparison over all elements).

A side-effect of this optimization is we also optimize OrderedDictionary.==, which performs an equality check on the keys property (which is an OrderedSet).[1]

[1] https://github.com/apple/swift-collections/blob/main/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary%2BEquatable.swift#L20-L22


Changes

From:

public static func ==(left: Self, right: Self) -> Bool {
  left.elementsEqual(right)
}

To:

public static func ==(left: Self, right: Self) -> Bool {
  left._elements == right._elements
}

We can also migrate OrderedSet.SubSequence. From:

public static func ==(left: Self, right: Self) -> Bool {
  left.elementsEqual(right)
}

To:

public static func ==(left: Self, right: Self) -> Bool {
  left._base._elements[left._bounds] == right._base._elements[right._bounds]
}

Test Plan

Five new tests are added:


Checklist

vanvoorden commented 5 months ago
2023-12-11-1

Here's what the benchmarks look like running locally.

vanvoorden commented 5 months ago
2023-12-11-2

Here are more benchmarks running locally.

lorentey commented 5 months ago

@swift-ci test