Peter71
Peter71

Reputation: 2300

SWIFT: performance of uppercaseString

I have a large file (25 MB) of text. I read it into a NSString var. I want to use "uppercaseString" to convert every char to upper case. But the function in so terribly slow, it needs minutes. Any tip to get it work much faster?

Added code:

if let path = NSBundle.mainBundle().pathForResource("GERMANU", ofType: "txt") {
    var error: NSError?
    if let data = NSData(contentsOfFile: path, options: NSDataReadingOptions(), error: &error) {           
        if let datastring = NSString(data: data, encoding: NSMacOSRomanStringEncoding) {
            var upper = datastring.uppercaseString
 ...

That's the code which works, but is slow. Only last row needs all the time.

Upvotes: 0

Views: 163

Answers (2)

Peter71
Peter71

Reputation: 2300

To me it looks like a poor library implementation. Using NSString.uppercaseString() is realy fast (half a second). So I will use this, but I'm developing in Swift because I like the language. So I don't want to switch back to old stuff.

Upvotes: 0

GoZoner
GoZoner

Reputation: 70145

String::uppercaseString is instantaneous; creating the string is not.

 # Long time
 12> var st : String = "".join(Array(count:25000000, repeatedValue: "a")) 
st: String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa..."

 # Short time
 13> st.uppercaseString
$R8: String = "AAAAAAAAAAAAAAAAAAAAAAAAAAAA..."

Given that you are using the Roman encoding, it is possible that the conversion to uppercase is non-trivial. Perhaps you can try another encoding (if any others are appropriate)? You might try the init?(... usedEncoding ...) variant and invoke fastestEncoding on the result to explore a bit.

Note: you can create a Swift string directly from a file with a particular encoding using:

if let datastring = String(contentsOfFile: path, encoding: ... , error: &error) {
  var upper = datastring.uppercaseString
}

Upvotes: 1

Related Questions