How can I get the string representation of a struct?

前端 未结 5 821
闹比i
闹比i 2021-01-30 16:04

For my application, it does not matter if the string is human readable or not.

5条回答
  •  攒了一身酷
    2021-01-30 16:05

    Using json or fmt.Sprintf, I make a benchmark,

    BenchmarkStructJson-8            1000000          1773 ns/op
    BenchmarkStructSprintSharp-8      200000          6139 ns/op
    BenchmarkStructSprint-8           500000          2763 ns/op
    BenchmarkStructSprintPlus-8       300000          4373 ns/op
    

    BenchmarkStructJson is using json.Marshal @Matheus Santana

    BenchmarkStructSprintSharp: `fmt.Sprintf("%#v", &a) @Ask Bjørn Hansen

    BenchmarkStructSprint: `fmt.Sprintf("%v", &a)

    BenchmarkStructSprintPlus: `fmt.Sprintf("%+v", &a)

    The result is, json.Marshal is better performance.

提交回复
热议问题