"case...when" VS hash
douglascamata opened this issue · 6 comments
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
hash is fastes, case is linear, hash is presumably O(1)
What do you mean by fair comparison? In your snippet function2 will be much much slower as you are creating Hash object every time.
@ixti I think that will depend on how many comparisons you do in the first function. What you think about this?
@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...
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.
Tutup ini sebagai pembelajaran buat kedepan nya