Skip to content

Commit 867109e

Browse files
committed
Add performance test case for JSON serialization
1 parent 150f071 commit 867109e

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

TestFoundation/TestNSJSONSerialization.swift

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import SwiftFoundation
1616
import SwiftXCTest
1717
#endif
18-
18+
import Dispatch
1919

2020
class TestNSJSONSerialization : XCTestCase {
2121

@@ -598,6 +598,7 @@ extension TestNSJSONSerialization {
598598
("test_invalidJsonObjectToStreamBuffer", test_invalidJsonObjectToStreamBuffer),
599599
("test_jsonObjectToOutputStreamInsufficeintBuffer", test_jsonObjectToOutputStreamInsufficeintBuffer),
600600
("test_booleanJSONObject", test_booleanJSONObject),
601+
("test_serialization_perf", test_serialize_perf),
601602
]
602603
}
603604

@@ -743,6 +744,35 @@ extension TestNSJSONSerialization {
743744
XCTAssertEqual(try trySerialize(jsonArr4), "[{\"a\":null},{\"b\":null}]")
744745
}
745746

747+
func test_serialize_perf() {
748+
let numItems = 20 // Number of elements in the payload
749+
let loops = 500 // Number of times to invoke serialization per measurement
750+
let concurrency = 4 // Number of concurrent threads
751+
var PAYLOAD = [String:Any]() // The string to convert
752+
753+
for i in 1...numItems {
754+
PAYLOAD["Item \(i)"] = Double(i)
755+
}
756+
757+
let queue = DispatchQueue(label: "testcaseQueue", attributes: .concurrent)
758+
let group = DispatchGroup()
759+
760+
self.measure {
761+
for _ in 1...concurrency {
762+
queue.async(group: group) {
763+
for _ in 1...loops {
764+
do {
765+
_ = try JSONSerialization.data(withJSONObject: PAYLOAD)
766+
} catch {
767+
XCTFail("Could not serialize to JSON: \(error)")
768+
}
769+
}
770+
}
771+
}
772+
_ = group.wait(timeout: .distantFuture) // forever
773+
}
774+
}
775+
746776
func test_nested_array() {
747777
var arr: [Any] = ["a"]
748778
XCTAssertEqual(try trySerialize(arr), "[\"a\"]")

0 commit comments

Comments
 (0)