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

Performance Comparison: Exceptions vs Break และ Return ใน Ruby

ผมสงสัยเสมอว่า exceptions ช้ากว่า flow control mechanisms อื่นๆ ใน Ruby มากแค่ไหน Exceptions ซับซ้อนกว่า "break" หรือ "return" มาก แต่เคย wrong ใน hunches ก่อน ลอง test ดู

Code ด้านล่างใช้ benchmark-ips gem เปรียบเทียบ relative performance ของ exiting loop via exception, break และ return ลองกับ MRI 2.2

require 'benchmark/ips' def exit_via_exception 5.times do raise RuntimeError end rescue end def exit_via_break 5.times do break end end def exit_via_return 5.times do return end end Benchmark.ips do |x| x.report("exception") { exit_via_exception } x.report("break") { exit_via_break } x.report("return") { exit_via_return } end 

ผลลัพท์ staggering Function 用 exception ช้ากว่า break และ return ครึ่งหนึ่ง

$ ruby exception_benchmark.rb Calculating ------------------------------------- exception 50.872k i/100ms break 125.322k i/100ms return 124.173k i/100ms ------------------------------------------------- exception 714.795k (± 2.7%) i/s - 3.612M break 3.459M (± 3.1%) i/s - 17.294M return 3.379M (± 3.0%) i/s - 16.888M 

This Isn't a Perfect Benchmark

มี issues สองอย่างไม่แน่ใจ compensate ยังไง เช่น exception และ break methods ต้อง return ทำมากกว่า method ที่แค่ return และสนใจว่า rescue exception เพิ่ม performance overhead ไหม แต่ไม่ rescue benchmark abort

แต่มันช้ามากจนผลลัพท์มีความหมายแม้ไม่ perfect

The Lesson We Learned?

ถ้าใช้ exceptions as flow control mechanism หยุดเลย! โดยเฉพาะ loop ที่ raise และ catch exceptions ซ้ำๆ

จะเปลี่ยนวิธีผมใช้ exceptions ไหม? น่าจะไม่ ผมทน slowness ได้ถ้า slowness เป็น exception to the rule :)

...But What About JRuby and RBx?

Josh Cheek (@josh_cheek) เขียน benchmark version เอง comprehensive กว่า รันกับ multiple ruby implementations ดู results ที่นี่ Break ยังคงชนะ :)