Is the ruby operator ||= intelligent?

前端 未结 5 2002
长发绾君心
长发绾君心 2020-11-29 10:30

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

5条回答
  •  盖世英雄少女心
    2020-11-29 10:48

    [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)
    

提交回复
热议问题