Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Ruby

ประเมิน Performance Cost ของการ Render Rails Partials

ได้ยินบางคนกังวลแยก large Rails views เป็น partials เล็กๆ: Render partial จริงๆ ใช้เวลาเท่าไหร่? Performance impact ของการเรียก partials จะ outweigh benefits ของ code readability?

ผมรัน numbers ให้ตัวอย่าง simple partial rendering เปรียบเทียบ inline rendering เพื่อ discuss tradeoff โค้ด benchmark ใน Rails app ใหม่ (กับ config.cache_classes = true):

app/views/test/show.html.erb
<% require 'benchmark'
Benchmark.bmbm do |x|
  x.report "inline" do
    10000.times do -%>
      <p>Hello!</p>
    <% end
  end
  x.report "partial" do
    10000.times do -%>
      <%= render partial: "hello" %>
    <% end
  end
<% end -%>
app/views/test/_hello.html.erb
<p>Hello!</p>

ผลลัพธ์ (Ruby 2.1 Rails 4.0.2, 2013 15" Retina Macbook Pro):

Rehearsal -------------------------------------------
inline 0.010000 0.000000 0.010000 ( 0.007045)
partial 0.970000 0.090000 1.060000 ( 1.050433)
---------------------------------- total: 1.070000sec
user system total real
inline 0.010000 0.000000 0.010000 ( 0.005529)
partial 0.920000 0.070000 0.990000 ( 0.997491)

所以 partial render 平均 ~0.1ms บนเครื่องเร็ว ช้ากว่า inline มาก แตพอที่จะไม่สังเกตตอนมี URL generation, Rails helpers, browser rendering time

Speed ไม่ใช่ทุกอย่าง

ถ้า performance rendering partials แย่มาก ผมยัง decide แยก huge views

มี phrase: Make It Work, Make It Right, Make It Fast ตอน fix view ใหญ่เกิน กำลังพยายามออกจาก "Make it Work" mode ไม่ข้ามไป "Make it Fast" ได้ จะทำโค้ด less maintainable และพลาด refactoring opportunities ที่นำไปสู่ caching opportunities และ performance benefits ใหญ่กว่า

ไม่รู้จนกว่าจะวัด

ไม่ต้องเชื่อ numbers ของผม แนะนำว่าไม่เชื่อ! Ruby Benchmark library มี tools 簡單รัน benchmarks มี tools profile full stack เช่น New Relic และ MiniProfiler ผม用ทั้ง 3 บ่อยในวันต่อวัน

ตอน profile ต้อง profile ใน production mode! Rails development environment auto-reloads classes และ views useful ตอน develop แตฆ่า performance numbers