From 9d69939f2c556ba75130f64dcd5c7fd742cc345a Mon Sep 17 00:00:00 2001 From: Nigel Tao Date: Sat, 29 Aug 2020 10:56:37 +1000 Subject: [PATCH] Have jsonfindptrs factor out escape_needed On a mid-range x86_64 laptop, processing the 181 MiB citylots.json file from github.com/zemirco/sf-city-lots-json: $ time gen/bin/example-jsonfindptrs < citylots.json > /dev/null Before this commit: real 0m7.550s After: real 0m7.333s Ratio: 1.03x --- example/jsonfindptrs/jsonfindptrs.cc | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/example/jsonfindptrs/jsonfindptrs.cc b/example/jsonfindptrs/jsonfindptrs.cc index 1e03d7f6..683af444 100644 --- a/example/jsonfindptrs/jsonfindptrs.cc +++ b/example/jsonfindptrs/jsonfindptrs.cc @@ -313,19 +313,21 @@ class JsonThing { // ---- -std::string // -escape(std::string s) { - for (char& c : s) { +bool // +escape_needed(const std::string& s) { + for (const char& c : s) { if ((c == '~') || (c == '/') || (c == '\n') || (c == '\r')) { - goto escape_needed; + return true; } } - return s; + return false; +} -escape_needed: +std::string // +escape(const std::string& s) { std::string e; e.reserve(8 + s.length()); - for (char& c : s) { + for (const char& c : s) { switch (c) { case '~': e += "~0"; @@ -377,11 +379,15 @@ print_json_pointers(JsonThing& jt, uint32_t depth) { case JsonThing::Kind::Object: g_dst += "/"; for (auto& kv : jt.value.o) { - std::string e = escape(kv.first); - if (e.empty() && !kv.first.empty()) { - return "main: unsupported \"\\u000A\" or \"\\u000D\" in object key"; + if (!escape_needed(kv.first)) { + g_dst += kv.first; + } else { + std::string e = escape(kv.first); + if (e.empty()) { + return "main: unsupported \"\\u000A\" or \"\\u000D\" in object key"; + } + g_dst += e; } - g_dst += e; TRY(print_json_pointers(kv.second, depth)); g_dst.resize(n + 1); }