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

Which would be faster?

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

OR json marshalling a struct like that?

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 + `"}`

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.