I have a question regarding the ||= statement in ruby and this is of particular interest to me as I\'m using it to write to memcache. What I\'m wondering is, does ||= check
[I removed my example that was less accurate than other's. I leave my answer for the benchmarks that might be interesting to some. My point was:]
So basically
CACHE[:some_key] ||= "Some String"
is the same as
CACHE[:some_key] = "Some String" unless CACHE[:some_key]
I'm more for the first syntax, but then it's up to you since readibility is a bit reduced in that case.
I was curious, so here's some benchmarks:
require "benchmark"
CACHE = {}
Benchmark.bm do |x|
x.report {
for i in 0..100000
CACHE[:some_key] ||= "Some String"
end
}
x.report {
for i in 0..100000
CACHE[:some_key] = "Some String" unless CACHE[:some_key]
end
}
end
user system total real
0.030000 0.000000 0.030000 ( 0.025167)
0.020000 0.000000 0.020000 ( 0.026670)