Skip to content

Commit 4247279

Browse files
committed
[stdlib] String.UnicodeScalarView: Optimize replaceSubrange
1 parent 42c8238 commit 4247279

File tree

1 file changed

+5
-11
lines changed

1 file changed

+5
-11
lines changed

stdlib/public/core/StringUnicodeScalarView.swift

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ extension String.UnicodeScalarView: RangeReplaceableCollection {
379379
/// string.
380380
///
381381
/// - Parameters:
382-
/// - bounds: The range of elements to replace. The bounds of the range
382+
/// - subrange: The range of elements to replace. The bounds of the range
383383
/// must be valid indices of the view.
384384
/// - newElements: The new Unicode scalar values to add to the string.
385385
///
@@ -388,18 +388,12 @@ extension String.UnicodeScalarView: RangeReplaceableCollection {
388388
/// removes elements at the end of the string, the complexity is O(*n*),
389389
/// where *n* is equal to `bounds.count`.
390390
public mutating func replaceSubrange<C>(
391-
_ bounds: Range<Index>,
391+
_ subrange: Range<Index>,
392392
with newElements: C
393393
) where C: Collection, C.Element == Unicode.Scalar {
394-
// TODO(String performance): Skip extra String and Array allocation
395-
let bounds = _guts.validateScalarRange(bounds)
396-
let utf8Replacement = newElements.flatMap { String($0).utf8 }
397-
let replacement = utf8Replacement.withUnsafeBufferPointer {
398-
return String._uncheckedFromUTF8($0)
399-
}
400-
var copy = String(_guts)
401-
copy.replaceSubrange(bounds, with: replacement)
402-
self = copy.unicodeScalars
394+
let subrange = _guts.validateScalarRange(subrange)
395+
_guts.replaceSubrange(subrange, with: newElements)
396+
_invariantCheck()
403397
}
404398
}
405399

0 commit comments

Comments
 (0)