新聞中心
最近因?yàn)槭褂肦uby寫一個(gè)多線程爬蟲,所以積累了一點(diǎn)小心得:

編輯推薦:Ruby入門教程與技巧大全
Ruby使用心得1、多使用Benchmark測(cè)試效率,以尋找高效的實(shí)現(xiàn),尤其是對(duì)于頻繁執(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)于字符串連接,盡量使用"<<",而不是"+=",因?yàn)閮烧咝氏嗖罹薮蟆?/p>
- 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 捕捉異常時(shí),如果沒有指定捕捉的異常類型,則默認(rèn)為StandardError。(If you write a rescue clause with no parameter list, the parameter defaults to StandardError.——參見Programming Ruby)
這點(diǎn)需要特別注意,因?yàn)槲覀兺?xí)慣性假設(shè)它會(huì)捕捉所有異常。譬如Net::HTTP獲取頁(yè)面如果超時(shí)會(huì)拋出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 —— 快速索引,查各種符號(hào)和用法很方便
Ruby User's Guide —— Ruby各方面精簡(jiǎn)介紹,入門不錯(cuò)
PLEAC Ruby —— Ruby的Cookbook
Ruby Example Code —— 簡(jiǎn)單直觀的樣例代碼,Ruby的HelloWorld
Ruby Essentials
分享標(biāo)題:Ruby使用心得匯總:尋找高效的實(shí)現(xiàn)
新聞來源:http://fisionsoft.com.cn/article/cdhieoo.html


咨詢
建站咨詢
