fastruby / fast-ruby

:dash: Writing Fast Ruby :heart_eyes: -- Collect Common Ruby idioms.
https://github.com/fastruby/fast-ruby
5.67k stars 376 forks source link

"case...when" VS hash #92

Closed douglascamata closed 1 year ago

douglascamata commented 8 years ago

I would love to see a fair comparison between "case...when" and hashes in cases like this:


def function(param)
  case param
    when :one then 1
    when :two then 2
  end
end

def function2(param)
  {
    one: 1,
    two: 2
  }[param]
end
gogainda commented 8 years ago

hash is fastes, case is linear, hash is presumably O(1)

ixti commented 8 years ago

What do you mean by fair comparison? In your snippet function2 will be much much slower as you are creating Hash object every time.

douglascamata commented 8 years ago

@ixti I think that will depend on how many comparisons you do in the first function. What you think about this?

ixti commented 8 years ago

@douglascamata I really can't answer this question. Benchmarking of your functions with moving one/two Hash map into a constant says that MAPPING[param] is 1.2x slower than case statement.

If I understand correctly on huge amount of keys both variants will perform equally. In any case comparison is pretty strange. when it's a constant mapping - i would go with hash, if it contains computable result depending on key - i would go with case...

mateusdeap commented 1 year ago

Seems to me this is a weird case as well. A Hash is a data structure whereas case is a control flow method. Although you could use them for the same purposes, if you want to just return some constant value for a given argument, that sounds like you want a Hash or a list of constants. It'd be weird to use a case statement for that.

Since the issue is quite old and the use case seems to be more some corner case for which one could use a case statement rather than a Hash, I'll be closing this for now.

inbdra commented 1 year ago

Tutup ini sebagai pembelajaran buat kedepan nya