Profiling php with xdebug and kcachegrind

Xdebug is a PHP extension which helps debugging and profiling php by providing a lot of valuable information. This information that Xdebug can provide includes stack traces and function traces in error messages with full parameter display for user defined functions, function name, file name and line indications. Support for member functions memory allocation, protection for infinite recursions. Xdebug also provides profiling information about PHP scripts, code coverage analysis and capabilities to debug your scripts interactively with your favorite debug client.

This post explains about Xdebug and gives a quick introduction on how to use these tools. Below are some of the tools needed to start profiling your php applications, using Ubuntu you will need these packages

sudo apt-get install php5-xdebug kcachegrind

Now you will need to add some setting for the php5 xdebug module, open the php5 conf.d xdebug configuration file and massage until it has similar settings.

sudo vim /etc/php5/conf.d/xdebug.ini
zend_extension=/usr/lib/php5/20060613/xdebug.so
 
[debug]
; Remote settings
xdebug.remote_autostart=off
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=localhost
xdebug.remote_port=9000
 
; General
xdebug.auto_trace=off
xdebug.collect_includes=on
xdebug.collect_params=off
xdebug.collect_return=off
xdebug.default_enable=on
xdebug.extended_info=1
xdebug.manual_url=http://www.php.net
xdebug.show_local_vars=0
xdebug.show_mem_delta=0
xdebug.max_nesting_level=100
;xdebug.idekey=
 
; Trace options
xdebug.trace_format=0
xdebug.trace_output_dir=/tmp
xdebug.trace_options=0
xdebug.trace_output_name=crc32
 
; Profiling
xdebug.profiler_append=0
xdebug.profiler_enable=0
xdebug.profiler_enable_trigger=1
xdebug.profiler_output_dir=/tmp
 
; output default to crc32 for a static callgrind profile.
xdebug.profiler_output_name=crc32
;xdebug.profiler_output_name=callgrind-%H-%R

Now you will need to get apache to reload in order for your settings to be applied.

sudo invoke-rc.d apache2 reload

Or you could try using a .htaccess file to turn on and off profiling?

php_flag xdebug.profiler_enable 1

This is where configuring xdebug comes down to the environment and personal or team preferences. How and when do you want your profile data to be created, if you set profiler_enable to 1 then xdebug will attempt to output data on every time php is called. You also have the option of only outputting profiles if profiler_enable_trigger=1 is configured and the GET variable XDEBUG_PROFILE is set in the page request as a trigger for xdebug to output the profile for that request.The output directory for xdebug can also be changed with the option xdebug.profiler_output_dir=/tmp

More soon

PHP V5.3 circular references and garbage collection

PHP V5.3 is to be released soon probably in the new year of 2009, and many of the new features in this release have been in the planning stages for a few years now. This release has been touted as “PHP V6 without native Unicode support,” PHP V5.3 has been developed into a feature-rich upgrade to the PHP V5 line. It’s designed to be a release to prepare developers for PHP V6 when it comes by adding many new features, cleaning up existing features by tweaking the functionality, fixing platform-specific issues, and deprecating old features that won’t be in future versions of PHP. In this “What’s new in PHP V5.3″ series, we’ll look at these new V5.3 features, and see how they are used and how they can be used in your Web application.

When PHP V5 was released in 2004, it was a giant step in regards to object-oriented programming (OOP) and design. Aadded several improvements, such as class visibility, proper constructors and destructors, type hinting, and a class-reflection API. Advanced objected-oriented programming was now possible in PHP, and allowed you to implement design patterns. PHP V5.3, are mainly syntax additions and performance improvements.

PHP and Garbage collection.

The topic of garbage collection and PHP should be very short as PHP has a fairly simple garbage collector that will collect an object when it is out of scope. The PHP knows the scope of an object is to use a reference counter, so that when the counter is at zero (this meaning there are no more references to this object), the object will be garbage collected and expunged from memory. This works well in most circumstances, but will become a problem in situations where an object references another object in a parent-child relationship. This situation causes, the reference counter for those object to not be collected, so the allocated memory PHP used by these objects stays in unreferenced memory and is not unallocated until the end, this can become a problem in large high traffic systems. An example of when this problem occurs.

PHP V5.2 and earlier Parent-child class relationship, Example of garbage collection issue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
class Parent 
{ 
    public function __construct() 
    { 
        $this->child = new Child($this); 
    } 
} 
 
class Child 
{ 
    public function __construct( 
        Parent $parent 
        ) 
    { 
        $this->parent = $parent; 
    } 
} 
?>

Every time you create an instance of the Parent class and then subsequently the instance goes out of scope, the memory is never released, so the script will grow and grow in memory usage. There is a user space solutions to this problem that would require creating a destructor for the parent class that will release the child object directly. This destructor would have to be called before removing the parent class reference. This complicates user space code.

In PHP V5.3, the garbage collector will detect these circular references and will be able to free up the memory used by them, so the PHP memory usage will remain flat as the script is executed. As each reference to the Parent class is removed, the Child class reference inside the Parent class will also be garbage collected.

New magic method __callStatic() and member handling

The PHP object interface has specially defined methods that can be used inside classes known as magic methods. When defined in a user space class, these methods provide functionality, and enable overloading, allowing a method to accept different types of parameters, and polymorphism allowing different data types to use the same interface. They also open the door to using different types of OOP programming methods, design patterns.

The new magic method is: __callStatic(). This works similar to the __call() magic method, which handles calls for methods that are not defined or visible. Now __callStatic() is for handling static method calls, this allows the ability to design method overloading. Example of using the new __callStatice method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
class Example
{ 
    public static function __callStatic( 
        $name, 
        $args 
        ) 
    { 
        echo "Called method $name statically"; 
    } 
 
    public function __call( 
        $name, 
        $args 
        ) 
    { 
        echo "Called method $name"; 
    } 
} 
 
Example::hello();       // outputs "Called method hello statically" 
 
$example = new Example; 
$example->hello();      // outputs "Called method hello" 
?>

PHP does enforce the definition of the __callStatic() method; it must be public, and it must be declared static. The __call() magic method must be defined public, just as all magic methods.

Dynamic static calls

One nice feature of PHP is variable variables. What this means is you can use the string value of a variable to specify the name of another variable. In other words, you could do something like what is shown below.

Variable variables

1
2
3
4
5
6
7
<?php
$x = 'y';
$$x = 'z';
echo $x;   // outputs 'y'
echo $y;   // outputs 'z'
echo $$x; // outputs 'z'
?>

The same concept can be used with functions, or even class methods, as shown below.

Variable function and class method names

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
class Dog 
{ 
    public function bark() 
    { 
        echo "Woof!"; 
    } 
} 
 
$class = 'Dog' 
$action = 'bark'; 
$x = new $class(); // instantiates the class 'Dog' 
$x->$action();     // outputs "Woof!" 
?>

New to PHP V5.3 is the ability to have the name of the class when specified be a variable when making a static call. This opens up a few new possibilities, as shown below.

Variable class naming

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
class Dog 
{ 
    public static function bark() 
    { 
         echo "Woof!"; 
    } 
} 
 
$class = 'Dog'; 
$action = 'bark'; 
$class::$action();  //outputs "Woof!" 
?>

This addition makes the variable-variables feature of PHP complete, allowing them to be used in just about every situation with PHP.

Let’s look at one more useful enhancement to using static methods and members: late static binding.

Late static binding

One of the more annoying things about PHP before V5.3 is how static methods and members are dealt with. Up until now, static references, such as those made with self or __CLASS__, are resolved in the class scope in which the function was defined. The problem is that the reference would be incorrect if the class was extended and the call was made from the new child class. Late static binding has been added in PHP V5.3 to alleviate this problem. To better illustrate, let’s create a class with a static method below.

Listing 5. Class Foo with static method test()

1
2
3
4
5
6
7
8
9
10
11
<?php
class Foo 
{ 
    protected static $name = 'Foo'; 
 
    public static function test() 
    { 
        return self::$name; 
    } 
} 
?>

Let’s extend this class. We’ll redefine the member $name in this child class.

Child class Bar that extends parent class Foo

1
2
3
4
5
6
<?php
class Bar extends Foo
{
    protected static $name = 'Bar';
}
?>

We make the static call in Foo.

Static method call test()

1
2
3
<?php
echo Bar::test(); 
?>

What is output from that call would be the string Foo. This is because the self::$name reference made in the test() method is done with the Foo class. The binding occurs this way because this is where the function is defined.

PHP V5.3 has added the keyword static to allow you to make a reference against the current class. So you will change the Foo class above to use this keyword in Listing 8, and we’ll see that Bar will instead be output.

Using the static keyword

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
class Foo 
{ 
    protected static $name = 'Foo'; 
 
    public static function test() 
    { 
        return static::$name; 
    } 
}
 
class Bar 
{ 
    protected static $name = 'Bar'; 
} 
 
echo Bar::test(); // outputs 'Bar'
?>

One thing to note about the static keyword is that it doesn’t work the same as how this works in the nonstatic context. This means that the normal inheritance rules do not apply to static calls. The static keyword will simply try to resolve the call in the current class instead of the class the function was defined in. This is an important thing to note.

Now that we have seen some enhancements with static methods and members, let’s take a look at some new classes added to a very useful part of PHP V5: the Standard PHP Library.

Standard PHP Library

The Standard PHP Library (SPL) is a collection of interfaces and classes added in PHP V5 designed to solve standard problems. These problems include having an object be iterateable, letting an object behave as if it was an array, or implementing a linked list. The advantage of using these classes and methods is that they are native to PHP, which means they are faster than if they were implemented in PHP itself. They also, in many instances, allow many of the internal functions of PHP to use these objects directly, such as how the Iterator interface allows you to use the foreach construct to iterate over the object.

PHP V5.3 adds a few more classes to SPL. One we referenced earlier is the implementation of a doubly linked list in the SPL class SplDoublyLinkedList. It is used by two other new SPL classes: SplStack, which implements a stack, and SplQueue, which implements a queue.

Let’s take a look at how you can use the SplStack class to implement a stack.

Using SplStack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
$stack = new SplStack(); 
 
// push a few new items on the stack 
$stack->push('a'); 
$stack->push('b'); 
$stack->push('c'); 
 
// see how many items are on the stack 
echo count($stack); // returns 3 
 
// iterate over the items in the stack 
foreach ( $stack as $item ) 
    echo "[$item],";   
// the above outputs: [c],[b],[a]
 
// pop an item off the stack 
echo $stack->pop(); // returns 'c' 
 
// now see how many items are on the stack 
echo count($stack); // returns 2
?>

The SqlQueue works in a similar fashion, but it works like a queue would (first item in, first item out; instead of last item in, first item out, like the stack). In addition, a heap implementation exists (SplHeap), as well as specific queue and heap implementations for certain situations (SplMinHeap, SplMaxHeap, and SplPriorityQueue).

Another useful addition is the SplFixedArray class, which, as the name implies, is a fixed-size array implementation. It is, however, rather fast — actually so fast that it’s been benchmarked to be 10-30 percent faster than the built-in array implementation in PHP. This speedup is due to the fact that the array is a fixed size, not a variable-sized one like the default PHP one is, and that non-numeric indexes are not allowed. Listing 10 shows how it’s used.

SplFixedArray

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
$array = new SplFixedArray(3); 
$array[0] = 'dog'; 
$array[1] = 'cat'; 
$array[2] = 'bird'; 
$a->setSize(4); // increase the size on the fly 
$array[3] = 'mouse'; 
foreach ( $array as $value ) 
    echo "[$value],";
 
Output: 
[dog],[cat],[bird],[mouse] 
?>

In addition, a few new iterator classes have been added: FilesystemIterator and GlobIterator. These work the same as the other iterator classes in PHP, but they are specially designed for certain instances.

One other change with SPL is that it is always enabled now in PHP V5.3. In previous versions of PHP V5, you could disable SPL at compile time, but as of PHP V5.3, this is no longer possible.

The new additions to SPL add some useful functionality to PHP that is easy to use, as well as implementations of data structures, such as doubly linked lists, stacks, heaps, and queues. These classes can be used to replace user space implementations you may have, which will gain increased speed and better integration with various PHP functions and constructs.

Summary

PHP has came a long way in the way of object-oriented programming support, from the weak support in the PHP V4 days to the much-improved additions in PHP V5 and tweaks with subsequent versions. Now, PHP V5.3 has gained some exciting improvements, including syntax enhancements such as the new __callStatic() magic methods, dynamic static calls, late static binding, static method, and member support. The new additions to SPL with the implementations of doubly linked lists, stacks, heaps, and queues, puts some common data structures at your fingertips and make them easy to use. Finally, the long-awaited circular garbage collector fixes memory and performance issues with self-referencing classes by implementing a much-improved garbage collector that properly releases memory for these circular instances. All of these features make PHP V5.3 a much stronger language for object-oriented programming.