Ruby使用心得匯總:尋找高效的實現(xiàn)
最近因為使用Ruby寫一個多線程爬蟲,所以積累了一點小心得:
51CTO編輯推薦:Ruby入門教程與技巧大全
Ruby使用心得1、多使用Benchmark測試效率,以尋找高效的實現(xiàn),尤其是對于頻繁執(zhí)行的代碼。Ruby執(zhí)行的效率本身比較慢,所以代碼選擇很重要。
- require 'benchmark'
- n = 100000
- Benchmark.bm { |x|
- x.report("gsub") {
- for i in 1..n
- a = "abcd\nef" * 10
- b = a.gsub(/\n/," ")
- end
- }
- x.report(" tr") {
- for i in 1..n
- a = "a\"bcd\nef" * 10
- b = a.tr("\n"," ")
- end
- }
上面執(zhí)行結(jié)果:
- user system total real
- gsub 2.312000 0.109000 2.421000 ( 2.438000)
- tr 0.656000 0.000000 0.656000 ( 0.672000)
兩者效率相差近四倍。
Ruby使用心得2、關(guān)于字符串連接,盡量使用"<<",而不是"+=",因為兩者效率相差巨大。
- require 'benchmark'
- Benchmark.bm { |b|
- b.report("+= ") {
- a = ""
- 100000.times { a += "foo" }
- }
- b.report("<< ") {
- a = ""
- 100000.times { a << "foo" }
- }
- }
執(zhí)行結(jié)果:
- user system total real
- += 22.390000 9.750000 32.140000 ( 35.671000)
- << 0.094000 0.000000 0.094000 ( 0.094000)
Ruby使用心得3、注意Ruby的異常類層次:
- Exception
- * fatal
- * NoMemoryError
- * ScriptError
- o LoadError
- o NotImplementedError
- o SyntaxError
- * SignalException
- o Interrupt
- * StandardError
- o ArgumentError
- o IOError
- + EOFError
- o IndexError
- o LocalJumpError
- o NameError
- + NoMethodError
- o RangeError
- + FloatDomainError
- o RegexpError
- o RuntimeError
- o SecurityError
- o SystemCallError
- o ThreadError
- o TypeError
- o ZeroDivisionError
- * SystemExit
- * SystemStackError
使用 rescue 捕捉異常時,如果沒有指定捕捉的異常類型,則默認為StandardError。(If you write a rescue clause with no parameter list, the parameter defaults to StandardError.——參見Programming Ruby)
這點需要特別注意,因為我們往往習慣性假設它會捕捉所有異常。譬如Net::HTTP獲取頁面如果超時會拋出Timeout::Error異常,其為Interrupt的子類,所以不能被無參的 rescue 捕獲。我就在這上面栽過跟頭。
Ruby使用心得4、這里有一些非常好的參考資料:
Ruby-Doc.org —— Ruby文檔的權(quán)威網(wǎng)站
Programming Ruby —— Ruby權(quán)威的文檔
Ruby Class and Library Reference —— 很方便的常見類的參考
Ruby QuickRef —— 快速索引,查各種符號和用法很方便
Ruby User's Guide —— Ruby各方面精簡介紹,入門不錯
PLEAC Ruby —— Ruby的Cookbook
Ruby Example Code —— 簡單直觀的樣例代碼,Ruby的HelloWorld
Ruby Essentials
【編輯推薦】