[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: The meaning of 'sugar' [Forked from Re: Why do we have ipairs?]
- From: Paige DePol <lual@...>
- Date: Fri, 13 Jun 2014 10:06:16 -0500
On Jun 13, 2014, at 9:40 AM, Ross Bencina <email@example.com> wrote:
> On 14/06/2014 12:17 AM, Paige DePol wrote:
>>> Is the "perfomance degradation" of using names (variables) instead
>>> of constants in an if-chain similar to what it does in your switch
>>>> statement? (You may try it with different kinds of variables.)
>> What "performance degradation" do you mean?
> I think Robert means to ask: what is the comparative performance of an if-chain vs. your switch statement implementation. And how does this comparison vary with different case types (e.g. string and number constants vs variables).
My switch statement performs in constant time, regardless of the number or type of case conditions present. All case values must be literal values that can be stored as keys in a Lua table.
>> I thought we were commenting on the degradation of code
> > readability by the use of "magic numbers" instead
> > of symbolic constants?
> That is one part of the discussion.
> Another part is about potential performance benefits of having a built-in switch construct. Does it always perform better? Or only when used with constants?
It always performs better than chained if statements, but also requires the use of constant case values. To support non-constant case values it would essentially turn into sugar for chained if statements, which I would then just use instead of a switch statement.
Which languages support case values that are not constant? A quick google did not turn up much information as nearly everything I could find talked about case values needing to be constant. Wouldn't a switch statement with non-constant case values would just wind up being sugar for chained if's?
I suppose a switch statement that allowed non-constant case values could be obtained by first trying the table lookup for constant case values, and then degrading to chained if statements for any non-constant case values. Though, to me, non-constant case values just seems strange which is why my patch did not implement them... honestly, it wasn't even something I thought of, to me case values have always been constant! ;)
Thank you for your post Ross, and thank you for your feedback Roberto, I am sorry I did not understand the meaning of your reply and I hope Ross had your intent right. I had not considered case values being non-constant and I think that oversight was probably impeding communications.