Integer vs string test time
-
I understand that
if vari=="0"
is slower thenif vari==0
. Is it better to doif vari.to_i==0
? -
It seems to be slower to do the conversion then do the comparison. To test something like this you can use the Time.now() method to make a simple stopwatch. Here is how I tested it.
def str_test() t = Time.now() (1..10000000).each{|i| "0" == "0"} puts(Time.now() - t) end def int_test() t = Time.now() (1..10000000).each{|i| "0".to_i == 0} puts(Time.now() - t) end
str_test ran in 6.922 and int_test ran in 8.406, feel free to run the test yourself.
-
Thanks, I will have to remember how to do that:)
Advertisement