Skip to content

Instantly share code, notes, and snippets.

@raphlinus
Created December 29, 2017 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphlinus/4e1539d1fdbab40586729e08ddc97f82 to your computer and use it in GitHub Desktop.
Save raphlinus/4e1539d1fdbab40586729e08ddc97f82 to your computer and use it in GitHub Desktop.
Simple JSON task using old "idiomatic" Swift
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
var baseTs: UInt64 = 0
func ts(_ label: String) {
let ts = mach_absolute_time()
print(label + String(format: ": %.3f", Double(ts - baseTs) * 1e-6))
}
let data = try Data(contentsOf: URL(fileURLWithPath: "/tmp/update.json"))
func benchOldJson() throws {
baseTs = mach_absolute_time()
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
ts("after json ser")
let obj = json as! [String: AnyObject]
ts("after cast")
let params = obj["params"] as! [String: AnyObject]
ts("after cast2")
let update = params["update"] as! [String: AnyObject]
ts("after cast3")
let ops = update["ops"] as! [[String: AnyObject]]
ts("after cast4")
var total = 0
var textlen = 0
for op in ops {
let opcode = op["op"] as! String
total += op["n"] as! Int
if opcode == "ins" {
let lines = op["lines"] as! [[String: AnyObject]]
for line in lines {
textlen += (line["text"] as? String)?.count ?? 0
}
}
}
ts("after sum n")
print("Old-style JSON result:", total, textlen)
}
try benchOldJson()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment