惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
博客园 - 三生石上(FineUI控件)
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
V
Visual Studio Blog
小众软件
小众软件
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MongoDB | Blog
MongoDB | Blog
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
The Cloudflare Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Engineering at Meta
Engineering at Meta
L
LangChain Blog
Martin Fowler
Martin Fowler
GbyAI
GbyAI
博客园 - 司徒正美

Nic Lin's Blog

謝明真 - 高效領導力的課後筆記 NFT 開發實戰!基礎智能合約入門 (3) NFT 開發實戰!基礎智能合約入門 (2) NFT 開發實戰!基礎智能合約入門 (1) 如何自我檢測 log4j CVE 漏洞 Rails 如何在資料寫入時記錄來源 IP 位置 如何經營工程師 Youtube 頻道 - Part 8 營收篇 如何經營工程師 Youtube 頻道 - Part 7 酸民文化篇 如何經營工程師 Youtube 頻道 - Part 5 設備器材篇 如何經營工程師 Youtube 頻道 - Part 4 後製剪輯篇 如何經營工程師 Youtube 頻道 - Part 3 文案企劃篇 如何經營工程師 Youtube 頻道 - Part 2 設備器材篇 如何經營工程師 Youtube 頻道 - Part 1 制訂頻道方向篇 如何經營工程師 Youtube 頻道 - Part 0 Rails 中避免 race condition 的最佳實踐(二) Rails 中避免 race condition 的最佳實踐(一) 10 分鐘整合 google sheet 做自動化開發功能週報 經營 Side Project 300 天所帶來的收穫及挑戰 我的 Youtube 影片製作流程 API 設計時必須注意的 HTTP header 底線問題 如何提升你的程式可讀性之實務技巧(三) 如何提升你的程式可讀性之實務技巧(二) 如何提升你的程式可讀性之實務技巧(一) Ruby 中使用 freeze 優化效能的時機 避免 React 中的 useEffect 無限 render 在 Rails 內輕量使用 Vue Component 的最佳實踐 如何在區域網路用 Docker 架設有 SSL 的 Gitlab 從被問到問人,那些我常問的面試問題 [Rails] 如何漂亮寫出可維護的 query (Maintainable Rails Query) 在已知長度情況下優化 slice 的性能
在 Rails 中能夠使用 explain + analyze
Nic Lin · 2018-07-04 · via Nic Lin's Blog

平常開發 Rails 在效能瓶頸時,除了會進 Database 測 explain 以外,也會在 console 裡面下同樣的語句。

不過遺憾的是,Rails 只能夠單純用 explain 而已,在 Postgres 中,如果僅僅只用 explain 分析,可能不是那麼準確,因為 explain 只是單純推測 query plan。

但如果下 explain analyze 就不一樣了,他除了會有推測分析還會有實際執行的分析,因為是拿這條 query 下去跑並回傳優化器的結果。

用最簡單的方式可以在 Rails console 就能呼叫

query = "EXPLAIN ANALYZE #{User.order(:created_at).to_sql}"
ActiveRecord::Base.connection.execute(query).each {|result| puts result}

#   (10.0ms)  EXPLAIN ANALYSE SELECT "users".* FROM "users" ORDER BY "users"."created_at" ASC
# {"QUERY PLAN"=>"Sort  (cost=10.52..10.78 rows=104 width=843) (actual time=4.872..4.890 rows=104 loops=1)"}
# {"QUERY PLAN"=>"  Sort Key: created_at"}
# {"QUERY PLAN"=>"  Sort Method: quicksort  Memory: 79kB"}
# {"QUERY PLAN"=>"  ->  Seq Scan on users  (cost=0.00..7.04 rows=104 width=843) (actual time=3.266..4.181 rows=104 loops=1)"}
# {"QUERY PLAN"=>"Planning time: 3.441 ms"}
# {"QUERY PLAN"=>"Execution time: 4.978 ms"}
# #<PG::Result:0x00007fc9d224e390 status=PGRES_TUPLES_OK ntuples=6 nfields=1 cmd_tuples=0>

參考來源: