# String.replacing performance

**URL:** <https://forums.swift.org/t/string-replacing-performance/68679>\
**Category:** Standard Library\
**Tags:** string, performance\
**Created:** [November 28, 2023, 7:06pm UTC](https://forums.swift.org/t/string-replacing-performance/68679 "2023-11-28T19:06:57Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![danielpunkass](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/danielpunkass/32/446_2.png) [@danielpunkass](https://forums.swift.org/u/danielpunkass)\
**Post date:** [November 28, 2023, 7:06pm UTC](https://forums.swift.org/t/string-replacing-performance/68679/1 "2023-11-28T19:06:57Z")

</div>

Recently, upon spotting a use of `Regex` in the wild to achieve the equivalent of a literal string replacement, I wondered about the performance implications of using `Regex` this way. To my surprise, I learned that using `String.replacing(Regex...)` is actually about 50% faster than using `String.replacing(String...)`. In my tests, I ran thousands of iterations for each scenario, including the use of Emoji characters, multiple replacements, etc, and in every test I made, a call like this:

```swift
myString.replacing(/foo/, with: "bar")

```

Is about 50% faster than:

```swift
myString.replacing("foo", with: "bar")

```

This made me wonder if Regex might have received more performance attention than the code path that `.replacing(String)` passes through, and if so, maybe it would make sense for the implementation of the latter to simply call through to the former?

After observing the difference in performance between the two above, I wondered how NSString would fare, so I changed the Swift String version to:

```swift
(myString as NSString).replacingOccurrences(of: "foo", with: "bar")

```

To my astonishment, _this_ version is around 50x faster than the Swift Regex case. Here is a typical Instruments Time Profiler run with each of the Regex, Swift String, and NSString cases running in succession:

 ![Screenshot 2023-11-28 at 9.58.32 AM](https://global.discourse-cdn.com/swift/original/3X/0/1/013c3273593cc787436178f6a87b8c2c53e01261.png)

I know there are sophisticated Unicode correctness issues at play in Swift String, and the C-based counterpart might be benefiting from speed of incorrectness. But these disparities, both the one that causes Regex to perform better than a literal string, and the one where NSString soundly wallops Swift String, made me wonder if there is room for improvements here.

I'd love to hear from anybody with experience in this area of the code base about whether they think there is merit in filing a bug or otherwise pursuing improvements here.

Daniel

---

<div class="post-metadata">

**Author:** ![scanon](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/scanon/32/2445_2.png) [@scanon](https://forums.swift.org/u/scanon)\
**Post date:** [November 28, 2023, 7:14pm UTC](https://forums.swift.org/t/string-replacing-performance/68679/2 "2023-11-28T19:14:10Z")

</div>

These API are somewhere that we know that there are good opportunities for large performance improvements, and relatively little effort has been directed at them so far, because most of our initial focus was on getting the API surface right.

Filing "hey, I tried a random synthetic benchmark and it was slow" bugs is not particularly useful--we already know that there's work to be done on these. But filing bugs of the form "this particular workload is very important to my use of the API" is quite useful, because we can add those meaningful cases to our benchmark suites and ensure that they are included in the improvements we make.

---

<div class="post-metadata">

**Author:** ![danielpunkass](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/danielpunkass/32/446_2.png) [@danielpunkass](https://forums.swift.org/u/danielpunkass)\
**Post date:** [November 28, 2023, 7:15pm UTC](https://forums.swift.org/t/string-replacing-performance/68679/3 "2023-11-28T19:15:41Z")

</div>

Makes sense. Thank you!

---

<div class="post-metadata">

**Author:** ![wadetregaskis](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/wadetregaskis/32/8494_2.png) [@wadetregaskis](https://forums.swift.org/u/wadetregaskis)\
**Post date:** [November 29, 2023, 4:08am UTC](https://forums.swift.org/t/string-replacing-performance/68679/4 "2023-11-29T04:08:05Z")

</div>

Maybe take a quick once-over of [this earlier thread](https://forums.swift.org/t/why-is-regex-slower-than-using-a-bunch-of-string-contains/66247) - not because it's the exact same situation (kind of reverse in fact) but because it has some good discussion about the current state of both `String` and `Regex` APIs. They need some love, in a nutshell. They are [open source](https://github.com/apple/swift-experimental-string-processing/blob/45fd8ec1189a7c91fa75590298272c4252b064e5/Sources/_StringProcessing/Regex/Core.swift#L80), by the way. 😉

---

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [November 29, 2023, 6:44am UTC](https://forums.swift.org/t/string-replacing-performance/68679/5 "2023-11-29T06:44:20Z")

</div>

> [@danielpunkass](#):
>
> This made me wonder if Regex might have received more performance attention than the code path that `.replacing(String)` passes through, and if so, maybe it would make sense for the implementation of the latter to simply call through to the former?

thanks for doing the extensive testing, i suspect this might be a situation where you’re running into the rough edges of swift overload resolution.

first, godbolt.

> **[Compiler Explorer - Swift (x86-64 swiftc 5.9)](https://swift.godbolt.org/z/PPhq4brjG)**
>
> public
> func a(\_ x:String, \_ y:String) -\> String
> {
> x.replacing("foo", with: "bar")
> }
> public
> func b(\_ x:String, \_ y:String) -\> String
> {
> x.replacing(/foo/, with: "bar")
> }

in the example with the `/foo/` regex literal, swift is calling `sSm17_StringProcessingSs11SubSequenceRtzrlE9replacing_4with15maxReplacementsxqd_0 __qd__ SitSlRd __AA14RegexComponentRd_0_SJ7ElementRtd__ r0_lF`, which demangles to [`(extension in _StringProcessing):Swift.RangeReplaceableCollection< where A.SubSequence == Swift.Substring>.replacing<A, B where A1: Swift.Collection, B1: _StringProcessing.RegexComponent, A1.Element == Swift.Character>(_: B1, with: A1, maxReplacements: Swift.Int) -> A`](https://swiftinit.org/docs/swift/swift/rangereplaceablecollection.replacing(_:with:maxreplacements:)?hash=1TG5U)

from the signature it says it is an extension on `RangeReplaceableCollection` where `Self.SubSequence == Substring` so it can take advantage of string-specific optimizations because it can specialize many of the types.

in your second example with the `"foo"` string literal, it is calling `sSm17_StringProcessingSQ7ElementRpzrlE9replacing_4with15maxReplacementsxqd ___qd_0_SitSlRd__ SlRd_0_ABQyd__ACRSABQyd_0_AGRSr0_lF` which demangles to [`(extension in _StringProcessing):Swift.RangeReplaceableCollection< where A.Element: Swift.Equatable>.replacing<A, B where A1: Swift.Collection, B1: Swift.Collection, A.Element == A1.Element, A1.Element == B1.Element>(_: A1, with: B1, maxReplacements: Swift.Int) -> A`](https://swiftinit.org/docs/swift/swift/rangereplaceablecollection.replacing(_:with:maxreplacements:)?hash=6Y22P).

this is an abstract function over `RangeReplaceableCollection` where `Element:Equatable` and isn’t likely getting specialized enough to benefit from optimization.

> [@danielpunkass](#):
>
> After observing the difference in performance between the two above, I wondered how NSString would fare, so I changed the Swift String version to:
> 
> ```swift
> (myString as NSString).replacingOccurrences(of: "foo", with: "bar")
> 
> ```
> 
> To my astonishment, _this_ version is around 50x faster than the Swift Regex case.

this probably has something to do with `NSString` being a concrete type and benefiting from more specialization than `Self:RangeReplaceableCollection`. it might be a good idea to add overloads to `String` and `Substring` that explicitly call the specialized implementations.

---

<div class="post-metadata">

**Author:** ![wadetregaskis](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/wadetregaskis/32/8494_2.png) [@wadetregaskis](https://forums.swift.org/u/wadetregaskis)\
**Post date:** [November 29, 2023, 4:33pm UTC](https://forums.swift.org/t/string-replacing-performance/68679/6 "2023-11-29T16:33:01Z")

</div>

> [@taylorswift](#):
>
> > [@danielpunkass](#):
> >
> > After observing the difference in performance between the two above, I wondered how NSString would fare, so I changed the Swift String version to:
> > 
> > ```swift
> > (myString as NSString).replacingOccurrences(of: "foo", with: "bar")
> > 
> > ```
> > 
> > To my astonishment, _this_ version is around 50x faster than the Swift Regex case.
> 
> this probably has something to do with `NSString` being a concrete type and benefiting from more specialization than `Self:RangeReplaceableCollection`. it might be a good idea to add overloads to `String` and `Substring` that explicitly call the specialized implementations.

Usually that happens automatically whenever Foundation is loaded.

And this is not uncommon - Foundation's `String` (i.e. `NSString`) functions are generally much faster than those for Swift's standard `String`. For both of the reasons already covered - incorrect / inappropriate use of overly generic algorithms, and simply inefficient implementations / algorithms.

---

<div class="post-metadata">

**Author:** ![blazej.sleboda](https://avatars.discourse-cdn.com/v4/letter/b/22d042/32.png) [@blazej.sleboda](https://forums.swift.org/u/blazej.sleboda)\
**Post date:** [November 17, 2025, 2:43pm UTC](https://forums.swift.org/t/string-replacing-performance/68679/7 "2025-11-17T14:43:26Z")

</div>

I generated the asm code for your initial Swift 5.9 version and found that 5.10 and 6.0.3 produce the same output, while 6.1 introduces changes. Your Godbolt setup is a very interesting tool to spot diffs in code produced by different compiler versions. Thx for the link.
