Json string are usually created and freed immediately. Thus, there should not be any downside in creating a larger buffer initially to avoid the cost of moving strings around in memory due to realloc() call.
The following script is used as benchmark to measure number of bytes reallocated: ovs-vsctl add-br br0 for i in `seq 0 100`; do ovs-vsctl add-port br0 p$i done ovs-vsctl del-br br0 'ds_bytes_relocated' coverage counter shows that the bytes relocated are 2.5Mbytes/sec and 17Kbytes/sec, before and after this patch applied, respectively. Signed-off-by: Andy Zhou <az...@nicira.com> --- lib/json.c | 2 +- lib/json.h | 10 ++++++++-- lib/jsonrpc.c | 6 ++++-- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/lib/json.c b/lib/json.c index dd85213..be76810 100644 --- a/lib/json.c +++ b/lib/json.c @@ -1462,7 +1462,7 @@ json_to_string(const struct json *json, int flags) { struct ds ds; - ds_init(&ds); + json_ds_init(&ds); json_to_ds(json, flags, &ds); return ds_steal_cstr(&ds); } diff --git a/lib/json.h b/lib/json.h index 3497035..c6b4ff5 100644 --- a/lib/json.h +++ b/lib/json.h @@ -30,14 +30,13 @@ * "should" be unique). */ +#include "dynamic-string.h" #include "shash.h" #ifdef __cplusplus extern "C" { #endif -struct ds; - /* Type of a JSON value. */ enum json_type { JSON_NULL, /* null */ @@ -127,6 +126,13 @@ enum { }; char *json_to_string(const struct json *, int flags); void json_to_ds(const struct json *, int flags, struct ds *); +/* Initialize 'ds', with reserved size suitable for typical Json objects */ +static inline void +json_ds_init(struct ds *ds) +{ + ds_init(ds); + ds_reserve(ds, 32 * 1024); /* pre allocate 32Kbytes buffer */ +} /* JSON string formatting operations. */ diff --git a/lib/jsonrpc.c b/lib/jsonrpc.c index b482777..81b173f 100644 --- a/lib/jsonrpc.c +++ b/lib/jsonrpc.c @@ -198,7 +198,8 @@ jsonrpc_log_msg(const struct jsonrpc *rpc, const char *title, const struct jsonrpc_msg *msg) { if (VLOG_IS_DBG_ENABLED()) { - struct ds s = DS_EMPTY_INITIALIZER; + struct ds s; + json_ds_init(&s); if (msg->method) { ds_put_format(&s, ", method=\"%s\"", msg->method); } @@ -238,7 +239,7 @@ jsonrpc_send(struct jsonrpc *rpc, struct jsonrpc_msg *msg) { struct ofpbuf *buf; struct json *json; - struct ds ds = DS_EMPTY_INITIALIZER; + struct ds ds; size_t length; if (rpc->status) { @@ -246,6 +247,7 @@ jsonrpc_send(struct jsonrpc *rpc, struct jsonrpc_msg *msg) return rpc->status; } + json_ds_init(&ds); jsonrpc_log_msg(rpc, "send", msg); json = jsonrpc_msg_to_json(msg); -- 1.9.1 _______________________________________________ dev mailing list dev@openvswitch.org http://openvswitch.org/mailman/listinfo/dev