lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


BTW, which one is faster? if-else or "a and b or c"?

On Thu, Apr 15, 2010 at 12:43 PM, Duncan Cross <duncan.cross@gmail.com> wrote:
On Thu, Apr 15, 2010 at 9:29 AM, GrayFace <sergroj@mail.ru> wrote:
> How about
> x = a > 1 ? b > 1 : c > 1
> ?

As Klaus said, the technique of using 'x and y or z' as a substitute
for 'x ? y : z' falls down whenever there's any possibility 'y' (in
your case, 'b > 1') could legimately be false/nil, so you do have to
be careful. Obviously, it's safe when 'y' is a number/string literal -
but if it's a function call or table lookup, there's a good chance you
can eventually get tripped up by this.

It's up to each individual user to decide whether this handy, but
fragile, shortcut is worth the tradeoff - code compactness vs. the bit
of extra care and thought you need to put in to make sure you're using
it properly.

-Duncan



--
NI!