File
Blob: src/workerd/tests/bench-json.c++
| 1 | // Copyright (c) 2023 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | #include <workerd/api/r2-api.capnp.h> |
| 6 | #include <workerd/tests/bench-tools.h> |
| 7 | |
| 8 | #include <benchmark/benchmark.h> |
| 9 | |
| 10 | #include <capnp/compat/json.h> |
| 11 | #include <capnp/message.h> |
| 12 | #include <kj/string.h> |
| 13 | #include <kj/test.h> |
| 14 | |
| 15 | // Example test, derived from capnproto's json test. |
| 16 | static void Test_JSON_ENC(benchmark::State& state) { |
| 17 | capnp::JsonCodec json; |
| 18 | // Perform setup here |
| 19 | |
| 20 | for (auto _: state) { |
| 21 | for (size_t i = 0; i < 10000; i++) { |
| 22 | // This code gets timed |
| 23 | KJ_EXPECT(json.encode(capnp::VOID) == "null"); |
| 24 | KJ_EXPECT(json.encode(true) == "true"); |
| 25 | KJ_EXPECT(json.encode(false) == "false"); |
| 26 | KJ_EXPECT(json.encode(123) == "123"); |
| 27 | KJ_EXPECT(json.encode(-5.5) == "-5.5"); |
| 28 | KJ_EXPECT(json.encode(capnp::Text::Reader("foo")) == "\"foo\""); |
| 29 | KJ_EXPECT(json.encode(capnp::Text::Reader("ab\"cd\\ef\x03")) == "\"ab\\\"cd\\\\ef\\u0003\""); |
| 30 | |
| 31 | json.setPrettyPrint(false); |
| 32 | kj::byte bytes[] = {12, 34, 56}; |
| 33 | KJ_EXPECT(json.encode(capnp::Data::Reader(bytes, 3)) == "[12,34,56]"); |
| 34 | |
| 35 | json.setPrettyPrint(true); |
| 36 | KJ_EXPECT(json.encode(capnp::Data::Reader(bytes, 3)) == "[12, 34, 56]"); |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | static void Test_JSON_DEC(benchmark::State& state) { |
| 42 | //Test R2BindingRequest, a more complex example |
| 43 | capnp::JsonCodec json; |
| 44 | capnp::MallocMessageBuilder responseMessage; |
| 45 | json.handleByAnnotation<workerd::api::public_beta::R2BindingRequest>(); |
| 46 | static constexpr kj::StringPtr dummy = |
| 47 | "{\"version\":1,\"method\":\"completeMultipartUpload\",\"object\":\"multipart_object_name4\",\"uploadId\":\"uploadId\",\"parts\":[{\"etag\":\"1234\",\"part\":1},{\"etag\":\"56789\",\"part\":2}]}"_kj; |
| 48 | |
| 49 | for (auto _: state) { |
| 50 | for (size_t i = 0; i < 100000; i++) { |
| 51 | auto responseBuilder = |
| 52 | responseMessage.initRoot<workerd::api::public_beta::R2BindingRequest>(); |
| 53 | json.decode(dummy, responseBuilder); |
| 54 | benchmark::DoNotOptimize(responseBuilder); |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | WD_BENCHMARK(Test_JSON_ENC); |
| 60 | WD_BENCHMARK(Test_JSON_DEC); |
| 61 | // Register both functions as benchmarks – we link benchmark_main so there's no need for a main |
| 62 | // function. |