Swift toInt() is excruciatingly slow

Originator:kamikaze.mark
Number:rdar://17255477 Date Originated:2014-06-10
Status:Open Resolved:
Product:OS X SDK Product Version:Xcode6-beta
Classification:Performance Reproducible:Always
 
toInt() is far slower than creating an NSScanner and scanning. There is no toDouble(), so I wrote one, then in timing it discovered this. All of these would be blown away by low-level scanning without alloc/release of an NSScanner.

import Cocoa

extension String {

func parseDouble() -> Double? {
	if self == "" {
		return nil
	}
	var scanner = NSScanner(string:self)
	var n = 0.0
	if scanner.scanDouble(&n) {
		return n
	} else {
		//NSLog("Invalid double \(self)")
		return nil
	}
}

func parseInt() -> Int? {
	if self == "" {
		return nil
	}
	var scanner = NSScanner(string:self)
	var n = 0
	if scanner.scanInteger(&n) {
		return n
	} else {
		//NSLog("Invalid integer \(self)")
		return nil
	}
}

func parseHexInt() -> Int? {
	if self == "" {
		return nil
	}
	var scanner = NSScanner(string:self)
	var n:CUnsignedInt = 0
	if scanner.scanHexInt(&n) {
		return Int(n)
	} else {
		//NSLog("Invalid hex integer \(self)")
		return nil
	}
}

}

let count = 10000
let s = "1234"
var t1 = CFAbsoluteTimeGetCurrent()
for var i = 0; i < count; ++i {
	var n = s.toInt()
}
var t2 = CFAbsoluteTimeGetCurrent()
NSLog("toInt took \(t2-t1) s")

t1 = CFAbsoluteTimeGetCurrent()
for var i = 0; i < count; ++i {
	var n = s.parseInt()
}
t2 = CFAbsoluteTimeGetCurrent()
NSLog("parseInt took \(t2-t1) s")

t1 = CFAbsoluteTimeGetCurrent()
for var i = 0; i < count; ++i {
	var n = s.parseDouble()
}
t2 = CFAbsoluteTimeGetCurrent()
NSLog("parseDouble took \(t2-t1) s")

// toInt took 4.900514960289 s
// parseInt took 0.793006002902985 s
// parseDouble took 0.780673027038574 s

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!