Commit 266c8377 authored by Yedidya Feldblum's avatar Yedidya Feldblum Committed by Facebook Github Bot

Fix an inefficiency in json-serializing a dynamic with sorted keys

Summary:
[Folly] Fix an inefficiency in json-serializing a `dynamic` with sorted keys.

The inefficiency is that, at each level of the `dynamic` which is map-typed, we effectively make a full copy of the `dynamic` object. This can be expensive.

Reviewed By: Gownta

Differential Revision: D4389671

fbshipit-source-id: 223739397f913d3e65a421a9a4dcb089ec757ec6
parent f47621ec
...@@ -15,7 +15,11 @@ ...@@ -15,7 +15,11 @@
*/ */
#include <folly/json.h> #include <folly/json.h>
#include <algorithm>
#include <cassert> #include <cassert>
#include <functional>
#include <boost/next_prior.hpp> #include <boost/next_prior.hpp>
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
...@@ -111,13 +115,13 @@ private: ...@@ -111,13 +115,13 @@ private:
indent(); indent();
newline(); newline();
if (opts_.sort_keys) { if (opts_.sort_keys) {
std::vector<std::pair<dynamic, dynamic>> items( using ref = std::reference_wrapper<decltype(o.items())::value_type const>;
o.items().begin(), o.items().end()); std::vector<ref> refs(o.items().begin(), o.items().end());
std::sort(items.begin(), items.end(), [](auto const& a, auto const& b) { std::sort(refs.begin(), refs.end(), [](ref a, ref b) {
// Only compare keys. No ordering among identical keys. // Only compare keys. No ordering among identical keys.
return a.first < b.first; return a.get().first < b.get().first;
}); });
printKVPairs(items.begin(), items.end()); printKVPairs(refs.cbegin(), refs.cend());
} else { } else {
printKVPairs(o.items().begin(), o.items().end()); printKVPairs(o.items().begin(), o.items().end());
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment