4 ms·
I like using the multiple-equality-comparison technique mentioned as the top example by the OP: foo == "bar" || foo == "baz" || foo == :sed || foo == 5
by danso 14y ago
I like using the multiple-equality-comparison technique mentioned as the top example by the OP:
foo == "bar" || foo == "baz" || foo == :sed || foo == 5
["bar", "baz", :sed, 5].include?(foo)
But that just has to be several times slower than the boolean check with the array usage, enough that you wouldn't want this refactoring in a mega-loop, right?
- stephth 14y agoIf it helps you/the code (readability, DRYness, ...) then go for it. Avoiding it on the basis of guessing it would make a difference is a slippery slope down premature optimization hell [1]. I'd say code away, and when/if you need to optimize, use a profiler. Likely you'll be surprised at what makes a difference and what doesn't really. edit: [1] Note that by guessing I'm referring to any optimizations that don't involve profiling your project, and that includes benchmarks of Ruby style, which are interesting to observe and can help you learn certain things about Ruby but are deceiving as far as understanding what actually makes a difference in your project. The sane way to optimize is to profile.
- xentronium 14y agoNot big enough, imho: https://gist.github.com/4e38f81f7871eb4e7f80 https://gist.github.com/4e38f81f7871eb4e7f80 Actually, static array version came ahead in my tests, which is probably due to memory allocations for strings.
- steveklabnik 14y ago> that just has to be several times slower This is why Matz gave us benchmark: steve at thoth in ~/tmp $ cat benchmark.rb require 'benchmark' n = 500000 Benchmark.bm do |x| x.report("==") do n.times do foo = "lol" foo == "bar" || foo == "baz" || foo == :sed || foo == 5 end end x.report("include?") do n.times do foo = "lol" ["bar", "baz", :sed, 5].include?(foo) end end end steve at thoth in ~/tmp $ ruby benchmark.rb user system total real == 0.370000 0.000000 0.370000 ( 0.367943) include? 0.550000 0.000000 0.550000 ( 0.551897)
- cheald 14y agoNow do it enough to trigger a couple of GC passes, and the #include? version looks even worse.
- knowtheory 14y agoJust from futzing around with Benchmark, it looks like the array allocation is the expensive bit. If you're not constantly reallocating the array you're checking against, it takes 1.5x more time to run. If you're allocating the array each time it's 3.5-4x more time. https://gist.github.com/4549975 https://gist.github.com/4549975