Re: [問題] 問一個語法上的問題~

看板Ruby作者 (godfat 真常)時間17年前 (2007/10/12 03:37), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串4/4 (看更多)
※ 引述《polarpolar (破啦貝爾)》之銘言: : 1. 最正規的就是 Catch Exceptions 來個 benchmark 吧 :D 我的結果: godfat benchmark 3.2$ ruby name.rb user system total real NameError 0.830000 0.100000 0.930000 ( 0.945779) local_variables.include? 0.090000 0.000000 0.090000 ( 0.098461) global_variables.include? 1.390000 0.040000 1.430000 ( 1.468565) many variables in global_variables.include? 1.710000 0.050000 1.760000 ( 1.797954) hash optimized many variables in global_variables 0.030000 0.000000 0.030000 ( 0.026852) 答案是變數很少的時候,local_variables.include? 又快又方便。 但是變數數量多一點時,include? 就會變得很慢了。 這時候用 exception 可能會方便些?要看狀況。 最快的還是預先建立 hash 再去 lookup :D 視情況挑一個用吧。 程式開始: require 'benchmark' Benchmark.bm{ |bm| n = 50000 puts 'NameError' bm.report{ n.times{ begin; var; rescue; end } } puts 'local_variables.include?' bm.report{ n.times{ local_variables.include? 'var' } } puts 'global_variables.include?' bm.report{ n.times{ global_variables.include? 'var' } } 10.times{ |i| eval("$a#{i} = 1") } puts 'many variables in global_variables.include?' bm.report{ n.times{ global_variables.include? 'var' } } puts 'hash optimized many variables in global_variables' bm.report{ vars = Hash[*global_variables.zip([true]*global_variables.size).flatten] n.times{ vars['var'] } } } : 我倒是對 method 得用 self.method 來取得 Method 物件比較感冒...... : 不過這是題外話啦。 同感! 不知道是不是 ecma script, or curry function 用慣了呢? :p 所以後來我做了個 alias_method :m, :method ... 有點蠢,不過要寫 ooo.method(:xxx) 真的挺煩的。 希望 ruby 能內建 curry function :p -- #!/usr/bin/ruby [露比] /Programming (Kn|N)ight/ 看板《Ruby》 # if a dog nailed extra legs that http://www.ptt.cc/bbs/Ruby/index.html # walks like an octopus, and Welcome ~Ruby@ptt~ # talks like an octopus, then ◢█◣ http://www.ruby-lang.org/ # we are happy to treat it as http://www.ruby-doc.org/ # if it were an octopus. http://www.rubyforge.org/ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.132.58.12

10/12 04:05, , 1F
global_variables 管的是 $ 開頭的變數, 取 'var' 一定失敗
10/12 04:05, 1F

10/12 08:17, , 2F
就是要失敗啊,沒差吧,worst case
10/12 08:17, 2F
文章代碼(AID): #173dj-rQ (Ruby)
文章代碼(AID): #173dj-rQ (Ruby)