Hacker News 中文摘要

RSS订阅

Jq的更快替代方案 -- A Faster Alternative to Jq

文章摘要

文章介绍了作者开发的JSON查询工具jsongrep,通过确定性有限自动机(DFA)实现高效查询,并提供了性能基准测试证明其速度优于jq、jmespath等同类工具。作者还解释了工具的设计理念和技术实现细节。

文章总结

文章标题:jsongrep 性能超越 {jq, jmespath, jsonpath-rust, jql}

核心内容概述

本文介绍了作者开发的 JSON 查询工具 jsongrep,重点解析了其底层基于确定性有限自动机(DFA)的搜索引擎原理,并通过基准测试证明了其性能优势。


工具亮点

  1. 设计理念

    • 将 JSON 文档视为树结构,查询语言设计为基于键/索引的路径正则表达式,可直接编译为 DFA。
    • jq 等解释型工具不同,jsongrep 通过预编译 DFA 实现单次遍历,避免回溯和递归开销。
  2. 查询语法示例

    • 点路径roommates[0].name
    • 通配符favorite_drinks[*]
    • 递归下降(* | [*])*.name(等价于 -F name 快捷操作)
    • 逻辑分支name | roommates
  3. 性能对比

    • 在 190MB 的 JSON 数据集上,jsongrep 端到端查询速度显著优于 jqjmespath 等工具(见下图)。
      性能对比图

技术实现

  1. 五阶段处理流程

    • JSON 解析 → 查询语法树生成 → NFA 构建(Glushkov算法) → DFA 转换(子集构造) → 树遍历匹配。
  2. 关键优化

    • 零拷贝解析:使用 serde_json_borrow 避免内存复制。
    • DFA 剪枝:跳过不匹配的子树,复杂度严格为 O(n)。
  3. 示例:查询 roommates[*].name

    • NFA 构建:生成线性状态链(无ε转移)。
    • DFA 转换:直接映射为确定性状态机。
    • 搜索过程:DFS 遍历时动态跳转状态,最终命中 roommates[0].name 节点。

基准测试

  1. 数据集
    | 规模 | 文件 | 大小 |
    |---|---|---|
    | 小型 | simple.json | 106 B |
    | 大型 | citylots.json | 190 MB |

  2. 对比工具
    jsonpath-rustjmespathjaqjql

  3. 结果摘要

    • 解析速度jsongrep 零拷贝解析最快。
    • 查询编译:DFA 构建耗时较高,但搜索阶段优势显著。
    • 端到端性能:综合表现领先其他工具 2-10 倍。

局限性

  • 功能定位:专注搜索而非数据转换(如不支持 jq 的过滤器或计算)。
  • 成熟度:新工具,尚未经过大规模实战验证。

延伸阅读

(注:原文中的技术细节和算法描述已简化,保留核心逻辑与性能结论。)

评论总结

以下是评论内容的总结:

  1. 工具性能争议

    • 部分用户质疑追求更快的CLI工具的必要性,认为现有工具如jq已足够快
      • "I personally have not encountered any case where a tool like jq feels incredibly slow" (Kovah)
      • "9/10 whatever tooling you are using now will be perfectly fine" (1a527dd5)
    • 也有用户赞赏性能优化
      • "as someone who always loved faster software... hat's off!" (hackrmn)
      • "Speed is good!" (coldtea)
  2. 语法比较

    • 有用户认为jsongrep的声明式语法比jq更简洁
      • "jsongrep is declarative: you describe the shape of the paths you want" (maxloh引用README)
      • "it's actually very good... after stumbling over slightly different syntax to jq" (keysersoze33)
    • 也有用户持保留意见
      • "Not a big fan of the syntax though" (coldtea)
      • "Jq is perfectly fine for quick peeking" (maxloh)
  3. 替代方案讨论

    • 有用户推荐其他工具如nushell和DuckDB
      • "nushell... its replaced all of these tools for me" (ifh-hn)
      • "get DuckDB to slurp the JSON natively" (quotemstr)
    • 极端观点认为应避免使用JSON
      • "The fastest alternative to jq is to not use JSON" (adastra22)
  4. 技术细节反馈

    • 对工具的技术实现和展示方式提出建议
      • "the horizontal violin graphs are nice, but all tools have the same colours" (jiehong)
      • "no official binaries for arm64 darwin" (steelbrain)
    • 对jq实现的赞赏
      • "jq's VM implementation... it's kind of mind-blowing" (bouk)
  5. 使用体验分享

    • 实际使用后的正面评价
      • "after reading more into jsongrep, it's actually very good" (keysersoze33)
    • 遇到的界面问题
      • "it had broken colors in light mode" (Bigpet)