4

Please have a look to below code

function GetAreaName($AreaCode)
{
  switch ($AreaCode) 
  {
    case 201: return 'New Jersey';
    case 202: return 'Washington';
    // this goes on till
    case 999: return '';
  }
}

Let's say if the AreaCode is 998 then it would have to go through so many cases! How could we optimize this function? (No using databases.)

I'm thinking to build an array and do a binary search over it? But this means every time the function is called the array will be rebuild? How do we build the array once, cache it and re-use every time this function is called?

Pacerier
  • 86,231
  • 106
  • 366
  • 634
user1809157
  • 285
  • 1
  • 6
  • 11

4 Answers4

7

Why not just use a hash table?

class Area {

private $areaCodes = array(
            201 => 'New Jersey',
            202 => 'Washington',
            // this goes on till
            999 => '';
        );

    function getStateByAreaCode ($areaCode) {

        if (array_key_exists($areaCode, $this->areaCodes)) {
           return $this->areaCodes[$areaCode];
        } else {
           return false;
        }

    }
}

Call it like this:

$area = new Area();
$city = $area->getStateByAreaCode(303);

Just save your class in a file and include it when you need it.

You Asked How to Prevent the Array From Being Created Every Request: By putting this in a class you at least keep it clean. It technically still gets created each request, but unless your array is enormous (WAY bigger than the area codes in the U.S.) it shouldn't pose a performance issue. If you are worried about building the array every time you have a request, then take a look at a code optimizer like APC or the Zend Optimizer. This essentially takes the byte code that PHP generates at run time and caches it.

Joshua Kaiser
  • 1,461
  • 9
  • 17
  • How do you implement this as a function? Particularly, how do you avoid reconstructing the array on every call? – erisco Nov 19 '12 at 05:43
  • @erisco I've filled out the code so it works inside of a class, and given some tips about optimization with a PHP code accelerator. If you don't want to go down the path of constructing an array on every call, then you could store it in a database table. However, I'd voucher that the connection to a DB the time to make the request is going to make a negligible difference compared to constructing an array. – Joshua Kaiser Nov 19 '12 at 06:16
2

Sounds like you should just store it in your database.

But if you can't do that, either abstract it into a config file of some kind and store it in some kind of persisted object, or just use a static variable:

function foo($key) {
    static $cache = array(1 => 'abc', 2 => 'def', 3 => 'ghi');
    if (array_key_exists($key, $cache)) {
        return $cache[$key];
    } else {
        //Somehow signal an error (throw an exception, return boolean false, or something)
    }
}

In the above, $cache would only exist once. (If you knew that the values would never be null, you could use isset instead of array_key_exists.)

This isn't very flexible though since changing the data requires you to edit your code. You typically want your data and your code to be decoupled.

That could mean storing it in some kind of file (json, xml, php, whatever), and loading it into some kind of structure that you only create once. You would then pass that object or array around wherever it was needed. (Or, if you wanted to be hacky, you could use a static class. I suggest against this though.)

Corbin
  • 33,060
  • 6
  • 68
  • 78
  • It seems static $cache will still be constructed for every php page request. I look around and found this http://stackoverflow.com/a/6062224/1809157 I might need to store it in a user session, at least it is only constructed once per user. I think it is still not the best which is only construct once through out the whole life of my web application. – user1809157 Nov 19 '12 at 06:47
  • @user1809157 Unless you use something like `apc`, there's no way to persist it between requests without contacting some kind of outside source (sessions are restored from files; databases require a connection; memcached and family require a connection; etc). The `foo` I posted would probably have marginally better performance than storing in a session. – Corbin Nov 19 '12 at 06:57
  • Hmm.. ok i'll just stick with your solution for now. Thanks! – user1809157 Nov 19 '12 at 07:25
2

Switch condition is evaluated once only:

In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster. ➫➫➫

There is no optimization required. However, read:
In PHP what's faster, big Switch statement, or Array key lookup

If you want to build a config file, you can consider something like:

$areas = array
(
  1 => 'abc',
  2 => 'def',
  ..
);

Then simply compare:

if (!isset($areas[$some_code]))
{
  // do something
}
else
{
  // ok
}
Community
  • 1
  • 1
ajreal
  • 46,720
  • 11
  • 89
  • 119
0

Try below pseudo code

$areas = array('201' => 'New Jersey',
                    '202' => 'Washington',
                    ......
                    ........
                    '999' => '');
function GetAreaName($AreaCode)
{


    if(isset($areas[$AreaCode])) {
        return $areas[$AreaCode];
    } else {
        // do something
    }

}
Ravi
  • 2,078
  • 13
  • 23