Skip to content

Commit a8c33d5

Browse files
Improve performance when removing an element from the middle of the array
Co-authored-by: Luciano Almeida <[email protected]>
1 parent 7517cd2 commit a8c33d5

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

Tests/SwiftAlgorithmsTests/TestUtilities.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,14 @@ func XCTAssertUnorderedEqualSequences<S1: Sequence, S2: Sequence>(
107107
missing.append(elt)
108108
continue
109109
}
110-
s1.remove(at: idx)
110+
// Since ordering does not matter, this is a small
111+
// optmization that avoid removing a index in the middle
112+
// of the array and having to slide all elements.
113+
let lastIdx = s1.index(before: s1.endIndex)
114+
if lastIdx != idx {
115+
s1.swapAt(idx, lastIdx)
116+
}
117+
s1.remove(at: lastIdx)
111118
}
112119

113120
if !missing.isEmpty {

0 commit comments

Comments
 (0)