LoginSignup
1
0

More than 3 years have passed since last update.

pluckとmapはpluckのが4倍速度早い

Last updated at Posted at 2019-03-08

大規模なRailsアプリケーションを開発した際に処理速度というのは非常に重要になってきます。
pluckはmapに比べて標準的なデータベースの探索のみなら、約4倍程の速度を出せると言われています。

以下はどちらで書いても結果は同じだが、pluckのが早いのでそっち使いたいところ。


users_name = User.all.map { |user| user.profile.name }

上と下ではどっちでも同じ


users_name = User.joins(:profile).pluck(:name)

*pluckは指定したカラムの配列を取得する
*上記の例はUserとProfileが1対1の関連

その他、書き方の例

mapでidが40以上のuserのidを取得する

2.4.1 :020 > User.select(:id).where(["id >= ?", 40]).map(&:id)
  User Load (0.4ms)  SELECT `users`.`id` FROM `users` WHERE (id >= 40)
 => [40, 41, 42, 43, 44, 45] 

pluckでidが40以上のuserをのidを取得する

2.4.1 :022 > User.where(["id >= ?", 40]).pluck(:id)
   (0.4ms)  SELECT `users`.`id` FROM `users` WHERE (id >= 40)
 => [40, 41, 42, 43, 44, 45] 

性別が1の人のidを取得

2.4.1 :047 > User.joins(:profile).where(["sex = ?", 1]).pluck(:sex)
   (0.4ms)  SELECT sex FROM `users` INNER JOIN `profiles` ON `profiles`.`user_id` = `users`.`id` WHERE (sex = 1)
 => [1, 1, 1, 1] 

*この場合「=」のみになる。

1対多の関連の時(Userがhas_manyでPermissionがbelongs_to)

以下の書き方。


Permission.joins(:user).pluck(:function_label)

【多のモデル】.joins(:1のモデル).pluck(:多のモデルのカラム名)

参考:where(["recorded_on < ?", Date.today]). ←このの書き方なに??

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0