Tencent / rapidjson

A fast JSON parser/generator for C++ with both SAX/DOM style API
http://rapidjson.org/
Other
14k stars 3.5k forks source link

performace comparison between snprintf and rapidjson wirter? #2258

Closed bethebest0622 closed 2 months ago

bethebest0622 commented 5 months ago

the output i need is a json string.

i could use snprintf with: snprintf(buff, sizeof(buff), "{\"productType\": \"usdt-futures\", \"marginMode\": \"crossed\", \"orderType\": \"limit\", \"marginCoin\": \"USDT\", \"size\":\"%s\", \"price\":\"%s\", \"force\": \"%s\", \"clientOid\": \"%s\", \"side\": \"%s\", \"symbol\": \"%s\"}", .....) rapidjson provide:

rapidjson::StringBuffer strBuf;
  rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf);
  writer.StartObject();
  writer.Key("productType");
  writer.String("usdt-futures");
  writer.Key("marginMode");
  writer.String("crossed");
  writer.Key("orderType");
  writer.String("limit");
  writer.Key("marginCoin");
  writer.String("USDT");
  writer.Key("size");
  writer.String("0.123123");
  writer.Key("price");
  writer.String("0.123123");
  writer.Key("force");
  writer.String("ioc");
  writer.Key("clientOid");
  writer.String("ioc");
  writer.Key("side");
  writer.String("buy");
  writer.Key("symbol");
  writer.String("BTC_USDT");
  writer.EndObject();

could you let me know which one is fast in a frequent-used situation?

pagict commented 2 months ago

in situation you described, I think the snprintf would win, since rapidjson is designated to a more general use, so more code for format adaption. and your example seems a rather fixed format.

but if taking maintainability, readability and flexiblity into account, rapidjson wins.

either way, you should profile them by yourself, because you know your context better than anyone else

miloyip commented 2 months ago

@bethebest0622 Please note that, writing JSON needs doing more things, for example, escaping some characters in string (e.g. if there is a " inside the string).