为何Rails中用ActiveRecord执行原生SQL比客户端/存储过程慢10倍?
Rails原生SQL执行比客户端慢10倍的原因排查
我在Rails中执行原生SQL用于夜间批处理的临时数据表创建与管理,原本计划最终将所有原生语句转为存储过程,但开发测试阶段为节省时间,使用了ActiveRecord::Base.connection.execute,结果却事与愿违。
DBeaver中执行耗时不到5秒
UPDATE tmp_reporting_sales_ia SET reporting_license_type = NULL, reporting_residency = 'N' ; -- Updated Rows 1304030
(注:即使执行前调用RESET QUERY CACHE;,结果一致)
ActiveRecord直接执行耗时超过50秒
ActiveRecord::Base.connection.execute("UPDATE tmp_reporting_sales_ia SET reporting_license_type = NULL, reporting_residency = 'N';")
日志输出:
D, [2022-12-07T22:16:13.231127 #7] DEBUG -- : (51585.2ms) UPDATE tmp_reporting_sales_ia SET reporting_license_type = NULL, reporting_residency = 'N'; => nil
调用存储过程耗时回到5秒以内
irb(main):024:0> ActiveRecord::Base.connection.execute("CALL reset_reporting_sales();")
日志输出:
D, [2022-12-07T22:25:06.252457 #7] DEBUG -- : (4297.1ms) CALL reset_reporting_sales(); => nil
这只是一个基础案例,其他更复杂的语句也存在同样问题。我希望在确定所有细节前不必处理存储过程,想了解是什么Rails开销导致这类语句执行慢10倍?
内容的提问来源于stack exchange,提问作者Yardboy
相关产品推荐
相关产品推荐

