gpt4 book ai didi

mysql - rails activerecord、mysql 和 mysql2 性能下降?

转载 作者:可可西里 更新时间:2023-11-01 08:52:07 25 4
gpt4 key购买 nike

我最近才从 Rails 2.3.5 升级到 Rails 3.2.7,并注意到我的某些查询的性能有所下降。我知道 Rails 3 ActiveRecord 在某些情况下比 Rails 2.3.5 慢,但基准测试让我感到惊讶,我只是想确保我没有遗漏任何东西。

我运行了以下查询,它在我的应用程序中非常受欢迎,作为基准

SELECT SQL_NO_CACHE table_name.* FROM table_name WHERE ((string_col = 'value') AND (int_col1 BETWEEN 5 AND 30)) ORDER BY int_col2 DESC LIMIT 1000

我检查过:

  • rails 3.2.7 与 rails 2.3.5
  • rails 3.2.7 与 mysql 适配器对比 mysql2
  • ActiveRecord.find_by_sql 与 ActiveRecord.connection.select_all

结果

轨道 3.2.7

rails 3.2.7,mysql 适配器,“select_all”:平均。 0.0148 秒
rails 3.2.7,mysql 适配器,“find_by_sql”平均。 0.0555秒

rails 3.2.7,mysql2 适配器,“select_all”:平均。 0.045秒
rails 3.2.7,mysql2 适配器,“find_by_sql”平均。 0.088秒

轨道 2.3.5

rails 2.3.5,mysql 适配器“select_all”:平均。 0.013秒
rails 2.3.5,mysql 适配器“find_by_sql”:平均。 0.0177 秒

虽然我的原始代码使用的是 ActiveRecord 查询 api,但我使用硬编码的 sql 作为基准测试,还验证了直接从 bash 命令行调用 mysql 是稳定的,并且上述数字来自 rails/mysql 适配器而不是数据库。

问题

这些差异是否合理?
“find_by_sql”和“select_all”之间的差异在 Rails 3.2.7 中比在 Rails 2.3.5 中大得多。
为什么 mysql2 比 mysql 慢?

最佳答案

我找到了这个 blog post其中讨论了 connection.select_all 如何使用较低级别的数据库调用来消除 find_by_sql 使用的一些较高级别的库。

Most calls in the standard ActiveRecord API return ActiveRecord “model” objects. However, there might be cases when you want to bypass the overhead of creating these full ActiveRecord objects, or maybe you want to query data that doesn’t have a corresponding ActiveRecord class. The connection adapter’s low-level query methods let you write your own SQL, and return “plain old data” as raw result tables.

关于 mysql v mysql2 mysql2 gem将返回值转换为 Ruby 本身使用的更复杂的 Ruby 类型,而不是字符串或 nil。但是,如果您需要这些,流式或异步查询 mysql2 gem 会更快。

关于mysql - rails activerecord、mysql 和 mysql2 性能下降?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12349318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com