Skip to content

Instantly share code, notes, and snippets.

@danieltmbr
Last active September 21, 2017 13:28
Show Gist options
  • Save danieltmbr/9f9e670078aa003b4991c6fddf965b23 to your computer and use it in GitHub Desktop.
Save danieltmbr/9f9e670078aa003b4991c6fddf965b23 to your computer and use it in GitHub Desktop.
Mesure performance of ranges compared to suffixing and prefixing
// Results
// Range vs Prefix&Suffix
// 5.88606303930283 vs 9.89196902513504 - Manipulating Array
// 5.65134799480438 vs 5.69769901037216 - Manipulating String
func measure(closure: (()->Void)) {
let start = Date()
closure()
let interval = Date().timeIntervalSince(start)
print(interval)
}
let values: [String] = Array(repeating: "a0", count: 2400)
// 5.88606303930283 sec
measure {
let numberOfPeers = values.count/6
var peers: [(ip: String, port: Int)] = []
for i in 0..<numberOfPeers {
let offset = i*6
let ip = values[offset..<offset+4].map{ String(Int($0, radix: 16)!) }.joined(separator: ".")
let port = values[offset+4..<offset+6].reduce(0) { $0 * Int(UInt8.max) + Int($1, radix: 16)! }
peers.append((ip: ip, port: port))
}
}
// 9.89196902513504 sec
measure {
var addresses = values.suffix(values.count)
var peers: [(ip: String, port: Int)] = []
var offset = 0
while addresses.count > 0 {
let ip = addresses.prefix(upTo: offset+4).map{ String(Int($0, radix: 16)!) }.joined(separator: ".")
addresses = addresses.suffix(from: offset+4)
let port = addresses.prefix(upTo: offset+6).reduce(0) { $0 * Int(UInt8.max) + Int($1, radix: 16)! }
addresses = addresses.suffix(from: offset+6)
offset += 6
peers.append((ip: ip, port: port))
}
}
extension String {
subscript (r: Range<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return String(self[Range(start ..< end)])
}
}
let string = values.joined()
string.count
// 5.65134799480438 sec
measure {
let numberOfPeers = string.count/12
var peers: [(ip: String, port: String)] = []
for i in 0..<numberOfPeers {
let offset: Int = i*6
let ip = string[offset..<offset+8]
// values[offset..<offset+4].map{ String(Int($0, radix: 16)!) }.joined(separator: ".")
let port = string[offset+8..<offset+12]
// values[offset+4..<offset+6].reduce(0) { $0 * Int(UInt8.max) + Int($1, radix: 16)! }
peers.append((ip: ip, port: port))
}
}
// 5.69769901037216 sec
measure {
var peers: [(ip: String, port: String)] = []
var text = string
while text.count > 0 {
let ipEnd = text.index(text.startIndex, offsetBy: 8)
let ip = String(text.prefix(upTo: ipEnd))
text = String(text.suffix(from: ipEnd))
let portEnd = text.index(text.startIndex, offsetBy: 4)
let port = String(text.prefix(upTo: portEnd))
text = String(text.suffix(from: portEnd))
peers.append((ip: ip, port: port))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment