Created
February 9, 2018 17:45
-
-
Save seifeet/f860e67e41e0b90b8397096b54bb3823 to your computer and use it in GitHub Desktop.
regex vs double for isNumeric
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
var timeDiff: Double = 0 | |
public extension String { | |
public var isNumericRegex: Bool { | |
return range(of: "(^-?[\\d]+$)|(-?[\\d]+[.,]{1}[\\d]+$)", | |
options: String.CompareOptions.regularExpression, range: nil, locale: nil) != nil | |
} | |
public var isNumericDouble: Bool { | |
return Double(self) != nil | |
} | |
public static func loremIpsum(ofLength length: Int = 445) -> String { | |
guard length > 0 else { return "" } | |
// https://www.lipsum.com/ | |
let loremIpsum = """ | |
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. | |
""" | |
if loremIpsum.count > length { | |
return String(loremIpsum[loremIpsum.startIndex..<loremIpsum.index(loremIpsum.startIndex, offsetBy: length)]) | |
} | |
return loremIpsum | |
} | |
} | |
func usingRegex(num: String) -> Double { | |
let start = DispatchTime.now() | |
if num.isNumericRegex == false { | |
} | |
let end = DispatchTime.now() | |
let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds // <<<<< Difference in nano seconds (UInt64) | |
let timeInterval = Double(nanoTime) / 1_000_000_000 // Technically could overflow for long running tests | |
return timeInterval | |
} | |
func usingDouble(num: String) -> Double { | |
let start = DispatchTime.now() | |
if num.isNumericDouble == false { | |
} | |
let end = DispatchTime.now() | |
let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds // <<<<< Difference in nano seconds (UInt64) | |
let timeInterval = Double(nanoTime) / 1_000_000_000 // Technically could overflow for long running tests | |
return timeInterval | |
} | |
for _ in 1...10000 { | |
// let diceRoll = String(Int(arc4random_uniform(600000))) | |
let diceRoll = String.loremIpsum() | |
timeDiff += (usingRegex(num: diceRoll) - usingDouble(num: diceRoll)) | |
} | |
print("Regex is slower by: \(timeDiff) seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment