alcohol / iso3166

A PHP library providing ISO 3166-1 data.
https://iso3166.thephpleague.com
MIT License
640 stars 59 forks source link

Improve performance with lookups #47

Closed garygreen closed 5 years ago

garygreen commented 5 years ago

At the moment when your searching it has to look thru all the countries in the array which is essentially O(n) performance.

Would it be an idea to keep a cached/compiled list for each type of lookup? That would mean you instantly return the data without any scanning taking it down to O(1) performance.

Example implementation:

private $lookupAlpha2 = ['AF' => '004', ...., 'US' => '840'];
private $countries = [
 '004' => [
    'name' => 'Afghanistan',
    'alpha2' => 'AF',
    'alpha3' => 'AFG',
    'numeric' => '004',
    'currency' => [
        'AFN',
    ],
],
'840' => [
    'name' => 'United States of America',
    'alpha2' => 'US',
    'alpha3' => 'USA',
    'numeric' => '840',
    'currency' => [
        'USD',
    ],
  ],
];

public function alpha2($alpha2) {
    if (isset($this->lookupAlpha2[$alpha2])) {
        return $this->countries[$lookupAlpha2[$alpha2]];
    }
}

The countries which are now keyed by the unique number code allows instant lookup.

Alternatively, if the lookups will be compiled automatically, we could just store the index of the country and use that rather than the numeric code.

garygreen commented 5 years ago

Possibly related to #48

alcohol commented 5 years ago

If this lookup really becomes a performance bottleneck for someone in their application, I am sure they are more than capable of wrapping it with a cached adapter themselves.