Skip to content

Instantly share code, notes, and snippets.

@raphlinus
Created December 29, 2017 19:09
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/6b0a7c54b563d9fe3b0cd1a1c87f9357 to your computer and use it in GitHub Desktop.
Save raphlinus/6b0a7c54b563d9fe3b0cd1a1c87f9357 to your computer and use it in GitHub Desktop.
Simple JSON task using Objective-C data structures
// 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 benchObjCLike() throws {
baseTs = mach_absolute_time()
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
ts("after json ser")
let obj = json as! NSDictionary
ts("after cast")
let params = obj["params"] as! NSDictionary
ts("after nsdict lookup")
let update = params["update"] as! NSDictionary
ts("after lookup2")
let ops = update["ops"] as! NSArray
ts("after lookup3")
var total = 0
var textlen = 0
for opRaw in ops {
let op = opRaw as! NSDictionary
let opcode = op["op"] as! String
total += op["n"] as! Int
if opcode == "ins" {
let lines = op["lines"] as! NSArray
for lineRaw in lines {
let line = lineRaw as! NSDictionary
textlen += (line["text"] as? String)?.count ?? 0
}
}
}
ts("after sum n")
print("ObjC-like result:", total, textlen)
}
try benchObjCLike()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment