PHP Classes

Some tips

Recommend this page to a friend!

      Faster PHP IP2Location  >  All threads  >  Some tips  >  (Un) Subscribe thread alerts  
Subject:Some tips
Summary:If you say "faster", try to make it faster
Messages:2
Author:Bodor Bence
Date:2016-07-25 18:43:57
 

  1. Some tips   Reply   Report abuse  
Picture of Bodor Bence Bodor Bence - 2016-07-25 18:43:57
Hi there.
Just dropping my 2 cents.

If your main goal is optimalization, you should really take it easy on the unnecessary function calls in your script. I mean this:

$ip_data = array();
foreach ($ip_list as $ip) {
// get all records
$records = $db->lookup($ip, \IP2Location\Database::ALL);

array_push($ip_data, array(
'ipaddr' => $records['ipAddress'],
'countryCode' => $records['countryCode'],
'regionName' => $records['regionName'],
'cityName' => $records['cityName'],
'lat' => $records['latitude'],
'long' => $records['longitude']
));
}

Is the same as this:

$ip_data = array();
foreach ($ip_list as $ip) {
// get all records
$records = $db->lookup($ip, \IP2Location\Database::ALL);

$ip_data[] = array(
'ipaddr' => $records['ipAddress'],
'countryCode' => $records['countryCode'],
'regionName' => $records['regionName'],
'cityName' => $records['cityName'],
'lat' => $records['latitude'],
'long' => $records['longitude']
);
}

Except the latter is 3 to 4 times faster (on a 100k list), because it doesn`t use a function call each time to add something to an array.

Also, array_key_exists($key, $search_array) is in most cases the same as isset($search_array[$key]) (not going into the edge cases right now) which is 2 times faster than array_key_exists.

Same goes for array_merge. If all you want to do is merge 2 simple arrays and you are going for speed, don`t be lazy to write a simple foreach to add in the values manually like in my first suggestion in this reply.

And as somebody before me mentioned, you should really test your script against the "slower" method in a real life exaplme too, before calling it faster.

P.S.: Can I make a code block in my reply somehow? Cause I can`t find any way to do it, or any description about it anywhere. I kinda find that strange on a site about scripting...

  2. Re: Some tips   Reply   Report abuse  
Picture of Chi H. Chi H. - 2016-07-25 20:43:27 - In reply to message 1 from Bodor Bence
This person was too lazy to test my script and your are to lazy to test my script and read the thread!

His pc has 4 cores and hyperthreading and I am using a Pentium G3528+vmware. Btw. your optimization is just about the test.php which is part of a contest and was not allowed to change. You can read the rules at the ip2location php library optimization contest (Sorry, can't copy and paste)!

I also wrote it's about binary search and spatial indexing and not so much micro optimization.

Feel free to find more micro optimization in the main class because I have done it, too!

I was the winner with 40% improvement over the original class!

Have a nice day!