Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-7749] Poor performance of String.replacingOccurrences(of:with:) in corelibs-foundation #3694

Closed
swift-ci opened this issue May 23, 2018 · 3 comments
Assignees

Comments

@swift-ci
Copy link
Contributor

Previous ID SR-7749
Radar rdar://56072687
Original Reporter gmilos (JIRA User)
Type Bug
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s Foundation
Labels Bug
Assignee @kevints
Priority Medium

md5: a019946d343f3e398647d7c8f94dddec

Issue Description:

The following piece of code:

import Foundation

let repeating = "\"."
let original = String(repeating: repeating, count: 1000000)

let start = Date()
_ = original.replacingOccurrences(of: "\"", with: "")
print("took: \(Date().timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate)")

takes over 20s on Linux (4.1 release, Ubuntu 14.04), in comparison to Darwin version, which takes 0.1s.

The cause is O(n^2) algorithm, or more precisely O(m*n), where m is number of matches, n is the length of the string, used here:

for cnt in 0..<numOccurrences {
let rangePtr = CFArrayGetValueAtIndex(findResults, backwards ? cnt : numOccurrences - cnt - 1)
replaceCharacters(in: NSRange(rangePtr!.load(as: CFRange.self)), with: replacement)
}

If we built up a new string afresh, appending segments that don't match, we'd have O(n) algorithm.

@swift-ci
Copy link
Contributor Author

Comment by Gregor Milos (Grzegorz Miłoś) (JIRA)

PR: #1620

@kevints
Copy link
Mannequin

kevints mannequin commented Oct 10, 2019

Rebased version of Gregor's PR: #2534

@kevints
Copy link
Mannequin

kevints mannequin commented Oct 15, 2019

5.1 version #2536

5.0 version #2537

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
@shahmishal shahmishal transferred this issue from apple/swift May 5, 2022
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant