Re: Re: What's faster using if else or arrays?

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

 



On Thursday, April 28, 2011, Jim Giner wrote:

> Arrays - using a  silly construct that probably still takes as much
> time to  evaluate machine-wise as anything else.  And as far as
> readability goes, it  is even sillier.   IMO.

I don't know so much about that ...

I'll use a global array to define an application-wide set and then use
in_array to branch dependent on whether some variable has a value that
is or is not a member of that set. Using a series of predicates in a
multiple OR, or using switch is a non-started for me for maintenance
reasons, and the alternative of storing the set of values in a
database is a lot slower. Here's an example:

FWIW, I've got a mapping application. Users can click on a map tile to
indicate a point of interest. However, they can also click on zoom
buttons, or pan buttons. These buttons are named 'plus', 'minus',
'left', 'right', 'up', and 'down' and I have these names in an
application-wide array:

$controls = array ('plus', 'minus', 'left', 'right', 'up', 'down');

The way that these map view controls are handled is very different to
the way a click on a map tile is handled. Somehow, the code is more
readable with:

if (in_array($clicked, $controls)){
 // ...
}

than with:

if ($clicked == 'plus' || $clicked == 'minus' || $clicked == 'left' || $clicked == 'right' || $clicked == 'up' || $clicked == 'down'){
 // ...
}

Even using switch isn't as clear IMO as that can intersperse the
options with several lines of code, which can make the logic harder to
spot.

However, the real benefit of using an array comes in making the code
easier to maintain. Drawing my map is a library routine, as is the
handler for the controls. However, the handling of clicks on map tiles
is different for each of the eight or nine contexts in which the
mapping is used. So the best way IMO of coding this is to test in each
page which element has been clicked and to either call a library
routine or a context-specific handler from there.

Now say, for example, that I want to augment the zoom functionality by
having a 'slider' that permits the user to go directly to a desired
zoom level. I can redefine the set of controls by simply changing the
global array. However, using the long if construct mandates that I
must amend the code of every page that uses the mapping, which makes
for a lot of extra work and is just plain silly IMO. IOW, using an
array can help avoid coding inconsistencies.

-- 
Geoff


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux