Re: Beginner Projects
- From: Lew <lew@xxxxxxxxxxxxx>
- Date: Thu, 30 Aug 2007 00:32:11 -0400
Roedy Green wrote:
On Wed, 29 Aug 2007 21:23:06 +0000 (UTC), Pseudo Silk Kimono
<Pseudo_Silk_Kimono@xxxxxxxxxxxxx> wrote, quoted or indirectly quoted
someone who said :
if ( (intValue % 2) == 0 )
this.isEven = true;
else
this.isEven = false;
I would collapse this to:
this.isEven = ( intValue %2 ) == 0;
Most likely isEven could be made local. Then you could shorten it
further to:
isEven = ( intValue & 1 ) == 0;
When many voices cry the same news, it reinforces the notion, doesn't it?
These idiomatic efficiencies are near no-brainers. Once you get used to them they become ingrained. One would never use an "if ... then ..." to set a boolean (or worse, a ternary with "...? true : false") once one is comfortable with assigning a boolean expression to a boolean variable.
Using a mask to determine even rather than modulo is based on the notion that masking is usually faster than modulo. OTOH, this counts as "premature optimization" in many cases. It's a good thing for prime calculations perhaps, because the calculation gets repeated so often there, but usually it's better to use whatever expression best reveals the algorithm to future maintainers. (That's why many excoriate the ternary operator, feeling that it is too "obscure". I like it, and it's been around enough decades that no one should find it too bizarre.)
--
Lew
.
- Follow-Ups:
- Re: Beginner Projects
- From: Roedy Green
- Re: Beginner Projects
- References:
- Beginner Projects
- From: Pseudo Silk Kimono
- Re: Beginner Projects
- From: Roedy Green
- Beginner Projects
- Prev by Date: Re: Beginner Projects
- Next by Date: Re: Beginner Projects
- Previous by thread: Re: Beginner Projects
- Next by thread: Re: Beginner Projects
- Index(es):