Homemade JSON

polaris · · 444 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Have you ever wanted to write your own json encoder/decoder? Sounds like a pain and compared to using a json pkg it is. In my case, I was developing a package that stored all data records as map[string][]byte. The key of each entry is the field name and all value types are stored as byte slice. By writing my own json encoder/decoder, just for this specific data structure, performance is much higher (3x to 4x). I implemented the same as json pkg ([]byte values are base64 encoded) so my output can be Unmarshaled using json pkg to verify everthing is working. My project is still in development, so undiscovered problems may be lurking. </p> <p><a href="https://play.golang.org/p/BzxiF7EhCf" rel="nofollow">See code</a></p> <hr/>**评论:**<br/><br/>icholy: <pre><p>Have your type implement the json.Marshaller interface. The json package will automatically use it.</p> <p><a href="https://golang.org/pkg/encoding/json/#Marshaler" rel="nofollow">https://golang.org/pkg/encoding/json/#Marshaler</a></p></pre>jayposs: <pre><p>I have thought of that, but would lose a little flexibility. I couldn&#39;t have the bufCapacity parameter.</p></pre>icholy: <pre><p>I smell premature optimization </p></pre>jayposs: <pre><p>Benchmark indicates about 20-25% faster on larger recMap using a &#34;just right&#34; bufCapacity. To be honest, its hard to get the size right, so I might remove this parameter and implement the Marshaler interface.</p></pre>arienh4: <pre><p>Why would you lose flexibility by adding a method? If you really need the <code>bufCapacity</code> (hint: you probably don&#39;t) you can always call that method directly. If not, use the <code>Marshaler</code> interface that calls your <code>toJSON</code> behind the scenes.</p></pre>komkahh: <pre><p>did you benchmark with encoding decoding of the values eg intToBytes bytesToInt? there is no benchmarking code? your data structure map[string][]byte does not support nesting, right? decoding encoded values with eg bytesToInt seams to be error-prone what if you are trying to decode something which is not an int? maybe if the json response changes. </p></pre>jayposs: <pre><p>This code is used to interact with the database, not respond to requests, so I might not have the issues you point out. Validation and conversion steps will be needed regardless of the json encode/decode.</p> <p>With regard to nesting, I think any value than can be converted to []byte could be used. So for example a struct could be json encoded and used as a value. I haven&#39;t tried that yet. Not sure if that is what you mean. </p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

444 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传