Showing posts with label optimize php. Show all posts
Showing posts with label optimize php. Show all posts

Monday, January 11, 2010

Simple Optimizing Tips for PHP Part IV - By Example (Part I)

Ss we write PHP code (or any language for that matter) we begin to start thinking about optimizing code. But even though our intentions are for "the greater good", we sometimes miss things that should be obvious.

Today's article takes a look at:

By Example


All developers progress at their own rate. As we progress, a few things that become evident is the existence of built-in php functions that can replace many of our own custom code, simply because we didn't know any other way. We also learn how to see repetition in our code and how to simplify it, when we should separate functionality into their own functions (or even classes!), and also just *know* when something will or will not work from personal experience. During this phase in life, we're becoming a senior developer.

Before we get to this point though, we are intermediate developers. Intermediate developers (in my honest opinion) is where a LOT of innovation comes from. It's from this level of developer that they are exploring PHP's full potential and how to exploit it to their benefit. When we are reaching the end of intermediate level and are looking to become the senior level developer on our team, we begin to try to search for ways to better ourselves as a developer. Unfortunately, such tutorials are very scarce and hard to find.

This tutorial is not to be the end-all be-all, but it is intended to help an intermediate find that next level. And we do this by examples.

Since even simple examples can lead to a book's worth of information, I plan to break this 4th part of Simple Optimizing Tips for PHP into sub parts. This will help reduce the amount of time it takes you to read this article, but also not try to slam too much information into your brain. Please keep in mind that while some of these examples won't exactly speed php's performance up, they will instead inadvertently teach you new methods and in turn try to warp your mind into a more sophisticated developer.

So without further ado, let's begin!

Our first example is the following function:


function multi_array_search($search_value, $the_array)
{
if (is_array($the_array))
{
foreach ($the_array as $key => $value)
{
$result = multi_array_search($search_value, $value);
if (is_array($result))
{
$return = $result;
array_unshift($return, $key);
return $return;
}
elseif ($result == true)
{
$return[] = $key;
return $return;
}
}
return false;
}
else
{
if ($search_value == $the_array)
{
return true;
}
else return false;
}
}


This function is perfectly valid, and works exactly as intended. However, there are a few things that one should notice right away:
1) The spacing and tabing of the data is not lined up nor consistant, making it hard to read.

2) The function is not taking advantage of the typehints that are now available in php 5.

3) Some of the code is a bit long and can be reduced to smaller lines without obfuscating the code.

4) The naming of some of the variables could be redefined to make understanding their purpose easier.

4) There exists absolutely no commenting in this function to explain it's purpose.

5) The possible return value is either boolean (true AND false) OR array!

6) The 2 parts of this function (the first if and the following else statements) could be refactored to make more sense and be more useful.

So now that we know this, how can we make this function better? Here is a revised, optomized solution.

/**
* @author John Doe
*
* Takes an array and searching for a value within.
*
* @param string $search_value
* @param array $search_array
* @return boolean // Returns true if a search value found, false if not.
*/
function multi_array_search($search_value, array $search_array) {
$search_result = false;
foreach($search_array as $key => $value) {
if(is_array($value)) {
# We have an array, so let's recursively search the subarray values
$search_result = multi_array_search($search_value, array_unshift($value));
} else {
# We have a string, so let's compare and see if we have a match
if($value == $search_value) return true;
}
}
return $search_result;
}


Notice that we are using the recursive method that was explained in my second tutorial on recursively looping through arrays. Also, we are now only returning a boolean value from this point on. In the case that we find a value, we return only a true, otherwise (and by default) we return false.

Now the above may or may not run faster (I haven't exactly run a test on this), but it is more simple, less code, and more understandable with comments that guide the way.

For the second part of By Example, we will be looking at redundant functionality and definitions, and learn how to better adjust our code to be more useful rather than bloated.

Monday, November 16, 2009

Simple Optimizing Tips for PHP Part II - Recursive Functions

As we write PHP code (or any language for that matter) we begin to start thinking about optimizing code. But even though our intentions are for "the greater good", we sometimes miss things that should be obvious.

Today's article takes a look at:

Recursive Functions

Functions are one of the most important tools we have for developing reusable, structured code. When we build our functions, we are mainly looking at ways to reduce redundancy and create effective ways to perform the same operations we use in either 1 script or all our scripts.

In our attempts to reduce redundancy, we inadvertently create more redundancy or miss opportunities to simplify how our code executes.

Consider this situation. We have a multidimensional array set that we want to display not only in a div, but also divs inside of divs. One method we could solve this with involves something like the following code:


$array = array("info" => array("employees" => array("name" => array(array("first" => "John",
"last" => "Doe",
),
array("first" => "Bob",
"last" => "Henry",
),
),
),
"departs" => array("building_1" => array("Sales",
"PR",
"HR",
),
"building_2" => array("Developers",
"Management",
),
),
),
"misc" => "Created in 2009",
);

function display_information(array $data_array) {
foreach($data_array as $key => $value) { // info
if(is_array($value)) {
foreach($value as $sub_key => $sub_value) {
if(is_array($sub_value)) {
foreach($sub_value as $sub_key2 => $sub_value2) {
if(is_array($sub_value2)) {
foreach($sub_value2 as $sub_key3 => $sub_value3) {
if(is_array($sub_value3)) {
foreach($sub_value3 as $sub_key4 => $sub_value4) {
echo "$sub_key4 => $sub_value4";
}
} else {
echo "$sub_key3 => $sub_value3";
}
}
} else {
echo "$sub_key2 => $sub_value2";
}
}
} else {
echo "$sub_key => $sub_value";
}
}
} else {
echo "$array_val";
}
}
}
While the above code works exactly as we need it to, it isn't exactly written the most efficient or optimized way. If you look at the code above, you can already start to see the redundancy involved with it. It's the exact same foreach statement whenever our condition of "is_array" rings true, and the exact same statement when it rings false. Plus, since we have to keep track of where we are in each of our loops, we get to the point to where our foreach loop parameters are extremely difficult to keep track of and the code in general is just a mess.

So how can we optimize the code above to be less redundant, and in return create a quicker, less line, and optimized solution? We do it by creating a recursive function.

A recursive function is just a method that calls itself from within itself. It helps reduce redundancy by applying similar logic to a result set without having to rewrite the exact same methods over and over again (as in the above code).


$array = array("info" => array("employees" => array("name" => array(array("first" => "John",
"last" => "Doe",
),
array("first" => "Bob",
"last" => "Henry",
),
),
),
"departs" => array("building_1" => array("Sales",
"PR",
"HR",
),
"building_2" => array("Developers",
"Management",
),
),
),
"misc" => "Created in 2009",
);

function display_information(array $data_array) {
foreach($data_array as $key => $value) { // info
if(is_array($value)) {
display_information($value);
} else {
echo "$array_val";
}
}
}


Nice isn't it? We take a 29 line function from our original example and turned it easily into a 9 line optimized function. This not only reduces the lines dedicated our function, but it also makes it easier to read, faster, and above all optimized!

Recursive functions can be used in many instances. The key for the developer is to recognize when it's needed by carefully examining the code and determine if it's needed. This example (while a bit exaggerated) will hopefully open your eyes and also teach you just one more simple thing you can do to create more optimized code for PHP!

Tune in next time for my next optimizing article on, Commenting.