<p>I am trying to parse a json object from a http response.</p>
<p>The first method I tried was not defining the structure:</p>
<pre><code>type Users []map[string]string
var users Users
</code></pre>
<p>Which surprisingly outperforms the method that defines the structure:</p>
<pre><code>type User struct {
UserID string `json:"userid"`
Name string `json:"name"`
}
var users []User
</code></pre>
<p>Is that normal or am I doing something wrong?</p>
<hr/>**评论:**<br/><br/>dean_karn: <pre><p>To expand on a few answers already given,.</p>
<p>Think past the actual parsing and to the usage of the data, a map will have lookup time and a struct won't.</p>
<p>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.</p>
<p>If parsing more than just a strings you'll have to do all the type checks and conversions yourself wherever you use the data.</p>
<p>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.</p></pre>dmikalova: <pre><p>Why wouldn't it be more performant? One is tossing strings into a map, the other is doing reflection to verify what goes where.</p></pre>ModerateBrainUsage: <pre><p>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.</p></pre>dmikalova: <pre><p>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.</p></pre>karma_vacuum123: <pre><p>use the benchmarking features of the <code>testing</code> library and find out for yourself</p></pre>dlsniper: <pre><p>Best answer by far to this. </p>
<p>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.</p></pre>itsmontoya: <pre><p>A struct will always be more efficient. </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传