Improve performance with lookups
Closed this issue · 2 comments
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.
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.