I am trying to parse a json object from a http response.
The first method I tried was not defining the structure:
type Users []map[string]string
var users Users
Which surprisingly outperforms the method that defines the structure:
type User struct {
UserID string `json:"userid"`
Name string `json:"name"`
}
var users []User
Is that normal or am I doing something wrong?
评论:
dean_karn:
dmikalova:To expand on a few answers already given,.
Think past the actual parsing and to the usage of the data, a map will have lookup time and a struct won't.
A map will be harder to reason what data is included, but a struct is clearly defined, especially if the data need to be passed to other functions.
If parsing more than just a strings you'll have to do all the type checks and conversions yourself wherever you use the data.
The small amount of overhead in parsing and clarity of your program will be far better served by using a struct 99.9999% of the time.
ModerateBrainUsage:Why wouldn't it be more performant? One is tossing strings into a map, the other is doing reflection to verify what goes where.
dmikalova:Reflections are slow in Go. But then you have to look how you will use your data. If you only use it once and throw it away. Use a map, if you are going to do constant lookups on the data, struct will be faster in the long run.
karma_vacuum123:It just seems like premature optimization to me. I'd rather have the statically typed, but slightly slower because of reflection data than a map, unless I run into an instance where it truly became the bottleneck.
dlsniper:use the benchmarking features of the
testing
library and find out for yourself
itsmontoya:Best answer by far to this.
Also, what's the point of not using a fixed struct? It makes life so much easier because you can remove the uncertainty about typos in key names and even have your favorite editor autocomplete them.
A struct will always be more efficient.
