Eager loading vs Lazy loading

Lazy Loading์€ ์—ฐ๊ด€๋œ ๋ฐ์ดํ„ฐ๋“ค์„ ์‹ค์ œ๋กœ ์ ‘๊ทผํ•˜๊ธฐ ์ „์—๋Š” ๋กœ๋”ฉํ•˜์ง€ ์•Š๋Š”๋‹ค. Lazy loading์˜ ์˜ˆ์‹œ๋ฅผ ๋ณด์ž.

users = User.where(status: 'active').joins(:profile)
users.each do |user|
  user_date << {
    name = user.name
    age = user.profile.age
  }
end

๋ฐ์ดํ„ฐ์— ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด users๋ฅผ ํ˜ธ์ถœํ•˜๋Š” 1๋ฒˆ์˜ ์ฟผ๋ฆฌ๋ฅผ ๋‚ ๋ฆฌ๊ณ , ์ดํ›„ do ๋ฃจํ”„์—์„œ user.profile.age ๊ตฌ๋ฌธ์— ์˜ํ•ด profile์— ์ ‘๊ทผํ•  ๋•Œ๋งˆ๋‹ค N๋ฒˆ์˜ ์ฟผ๋ฆฌ๋ฅผ ์ถ”๊ฐ€๋กœ ๋‚ ๋ฆฌ๊ฒŒ๋œ๋‹ค.

์ด๋Ÿฐ ๋ฌธ์ œ๋ฅผ N+1 Problem๋ผ๊ณ  ํ•œ๋‹ค. ๊ทผ๋ณธ์ ์œผ๋กœ ORM์—์„œ Lazy Loading์„ ์‚ฌ์šฉํ•  ๋•Œ ๋ฐœ์ƒ๋˜๋Š” ๋ฌธ์ œ์ธ ๊ฒƒ์ด๋‹ค.

Rails๋Š” ์ด๋Ÿฐ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด includes๋ผ๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ์ œ๊ณตํ•ด์ค€๋‹ค.

With includes, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries

์ž ์•„๋ž˜์ฒ˜๋Ÿผ ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•ด๋ณด์ž.

users = User.where(status: 'active').includes(:profile)
users.each do |user|
  user_date << {
    name = user.name
    age = user.profile.age
  }

์œ„ ์ฝ”๋“œ์—์„œ๋Š” ๋‘ ๋ฒˆ์˜ ์ฟผ๋ฆฌ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. users ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ๋•Œ ํ•œ๋ฒˆ, users์— ๋Œ€ํ•œ profile์„ ์ฐพ๋Š”๋ฐ ํ•œ๋ฒˆ. ์ด๋Ÿฌํ•œ ๋กœ๋”ฉ ๋ฐฉ์‹์„ eager loading์ด๋ผ๊ณ  ๋ถ€๋ฅธ๋‹ค.

๊ทธ๋Ÿผ joins๊ฐ€ includes๋ณด๋‹ค ํšจ์œจ์ ์ธ ๊ฒฝ์šฐ๋Š” ๋ฌด์—‡์ผ๊นŒ? ์•„๋ž˜์ฒ˜๋Ÿผ ํ•„ํ„ฐ์˜ ์—ญํ• ์„ ํ•  ๊ฒฝ์šฐ ํšจ์œจ์ ์ด๋‹ค.

users = User.joins(:profile).where('profile.status = ?', 'active')
users.each do |user|
  user_date << {
    name = user.name
  }
end

do ๋ฃจํ”„์—์„œ profile์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , profile์€ ๋‹จ์ง€ filter์˜ ์—ญํ• ์„ ํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

Last updated