doujia9833
doujia9833
2015-01-30 17:15
浏览 160

GoLang-编码/json.Marshal或fmt.sprintf?

Which would be faster?

data := fmt.Sprintf("{\"TEST\":3, \"ID\":\"%s\"}", Id)

OR json marshalling a struct like that?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyuluan7494
    dongyuluan7494 2015-01-31 03:39
    已采纳

    Highly depends on what you're trying to do, you should benchmark it and see.

    However for your very specific example, the fastest way is just use basic string concat like :

    data := `{"TEST":3, "ID":"` + Id + `"}`
    
    点赞 评论
  • dtot74529
    dtot74529 2018-01-05 00:38

    In the case of JSON with basic data types (string, bool, int) fmt.Sprintf is faster. Benchmarking shows that it is on the order of twice as fast as json.Marshal for rendering a very small JSON object, with the spread in performance increasing as more data is added.

    The benchmark results for rendering a JSON object using both methods (10,000,000 times each for clarity) are as follows:

    Benchmarks for rendering a small JSON object
    Time taken to render JSON object using json.Marshal:     8.747821898s
    Time taken to render JSON object using fmt.Sprintf:      4.452937712s
    
    Benchmarks for rendering a larger JSON object
    Time taken to render JSON object using json.Marshal:     32.100388801s
    Time taken to render JSON object using fmt.Sprintf:      10.392861696s
    

    Note that these results do not hold if your JSON object contains more complex data types like lists and nested objects.

    点赞 评论

相关推荐