doulongti5932 2017-12-23 12:22
浏览 61

Crystal:包含大字符串的结构的json慢速序列化

I'm wondering why json serialization of structs containing large strings is slow in Crystal.

The following code performs rather poorly:

struct Page
  include AutoJson
  field :uri, String
  field :html, String
end

page = Page.new(url, html) # html is a string containing ±128KB of html

page.to_json

Whereas the following code in Javascript (Node.js) or Go is pretty much instantaneous (like x10~x20 times faster):

Node.js

page = { url: url, html: html }
JSON.stringify(page)

Go

type Page struct {
  Uri string `json="uri"`
  Html string `json="html"`
}

page = Page{ uri, html }

json, _ = json.Marshal(page)  

Considering Crystal is usually very fast (on par with Go and much faster than V8 Javascript) it kinda left me wondering what was going on here.

I've been experimenting with the Crystal code a little bit and it seems as if the incriminating bit here is the double-quote string escaping of large strings (which is obviously required when serializing json objects). But why would it take so long, I don't know (multiple allocations, copies?).

For the record, in these example, html is a roughly 128KB html file loaded from disk using whatever synchronous method is available. File reading operations are obviously not taken into consideration when benchmarking these snippets.

  • 写回答

3条回答 默认 最新

  • duanlei1957 2017-12-23 20:46
    关注

    Like many other APIs, Crystal's JSON implementation is not really optimized for speed. It is merely to get it working. And that is actually already quite fast for most use cases, but there are certainly huge improvements awaiting.

    I'm not sure what's exactly the reason here. It might be related to string escaping, allthough this need to be done in other languages as well.

    Regarding the comparison to JavaScript, transforming an object to JSON is actually quite performant because this is a native datatype of JavaScript and implemented very efficiently. This is not dynamic code evaluation but compiled in the Javascript VM.

    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来