0

I was recently reviewing some code when a simple question came up…

What’s the fastest way to output a segmented string?

1
2
3
4
5
echo '<div>';
echo '<span>';
echo 'This is a random number: ' . mt_rand(1,100);
echo '</span>';
echo '</div>';

– OR –

1
2
3
4
5
6
7
$html = '';
$html .= '<div>';
$html .= '<span>';
$html .= 'This is a random number: ' . mt_rand(1,100);
$html .= '</span>';
$html .= '</div>';
echo $html;

My initial guess was that calling echo as little as possible during a request would end up performing better as there would be no need to interact with an output buffer or perform other logic tied to STDOUT.

I ended up asking a few friends and colleges what they thought about the question and most responded with “hu?” After telling them that I was in fact serious the majority of their opinions fell on echo being the winner. Still, others thought of ways to get a segmented string out faster, like pushing them onto an array and executing echo implode(”, $array);

This difference of opinion got me thinking about what was truly the most efficient way to output a collection of strings? Curiosity got the best of me and I quickly setup some profiling tests using my Bench Class to find out the answer.

Profiling Setup

I used the following code in order to get enough data points for a solid performance comparison.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$samples = 40;
$sets = array(10,20,50,100,500,1000,1500,2000,2500,3000);
$results = array();
foreach($sets as $iterations) {
  $results[$iterations] = array();
  for($i=0; $i<$samples; $i++) {
    Bench::start();
    for($j=0;$j<$iterations;$j++) {
      // ... Output Test ...
    }
    $results[$iterations][] = Bench::stop();
    Bench::reset();
  }
}

Tests

I tested the performance on four different methods of outputting data…

(more…)

4

A couple weeks ago I was looking for a simple way to make AJAX requests on admin or public WordPress pages from a theme or plug-in. After a bit of searching I could not find the solution I was looking for – so I built my own, AHAX.

AHAX is a drop-in solution that allows theme or plug-in developers to take advantage of a very simple and streamlined way of making AJAX requests.

Live Example

My goal was to make the process of setting up an AJAX request simple as possible. Below is a (very) simple example where I use AHAX to get a random number from the server on user request.

...

Under The Hood

To create the example above I had to do two simple things. First, create the PHP function that handles the AJAX request in my theme’s function.php file and associate it with a specific AHAX action using ahax::bind(…). Second, create an instance of the AHAX JavaScript class and use its post method to make a request to the previously mentioned PHP function.

Back-End

PHP

1
2
3
4
5
6
ahax::bind( 'get_random_number', 'generate_number' );
function generate_number($output) {
  $max = abs( ( int ) $_POST['max'] );
  $output = mt_rand( 0 , ( $max < = 1000 ? $max : 1000 ) );
  return $output;
}

Front-End
JavaScript

1
2
3
4
var ahax = new AHAX();
ahax.post('get_random_number', {max:1000}, function(response) {
  jQuery('#ahax_number').html(response);
});

Breaking It Down

With this plugin I’ve attempted to make the process of creating an AJAX request as simple as possible by centering everything around an action.

The Action

In the code example above get_random_number is the action of the AHAX request. The static method ahax::bind(…) is used to create a WordPress filter that corresponds to the JavaScript ahax.post(…) method’s first argument.

A valid action is only allowed to consist of a-z, A-Z, and underscore ( _ ) characters.

(more…)

2

Introducing a simple, yet deceivingly useful, micro benchmarking / timer class called Bench.

I’ve found myself on more than a few occasion using this familiar block of code in order to quickly narrow down a bottleneck or test a specific section of code.

1
2
3
4
$start = microtime(true);
// [Some Code To Test]
$time = (microtime(true) - $start);
echo $time.' Seconds';

This is a crude but effective way of finding out how long it takes to get from line A to line B. On the down-side, this technique is annoying to implement, only measures time between two points, and makes code look very cluttered — so I started developing Bench.

Features

Bench offers more than just clean looking code or timing between two lines. Its goal is to be more powerful and reusable than simple Microtime Arithmetic while trying avoid stepping on anyone’s toes (*cough* *cough* Xdebug, see below).

Start and Stop

Bench can perform the same operation as the example above but in a much cleaner manner.

1
2
3
Bench::start();
// [Some Code To Test]
echo Bench::stop() . ' Seconds.';

Marks

“Marks” are simply points in code that one would like tracked by Bench. They are easy to use, quick to implement, and very useful when tracking multiple parts of a script/request.

1
2
3
4
5
6
7
8
9
Bench::start();
// [Application Bootstrap]
Bench::mark('bootstrap');
// [Database Connection Opened]
Bench::mark('database');
// [Data Processing + Manipulation]
Bench::mark('processing');
// [HTML Creation]
Bench::mark('html');

Each call to mark() creates a Mark Array that contains the id, microtime of when it occurred, seconds since start, and seconds since the previously called mark.

(more…)

0

I’ve developed a new class for WinCache that wraps around the wincache_ucache* functions. The goal of this class/project is to improve — and add to — the functionality and usability of WinCache’s User Cache feature.

Basic Usage

Below is a quick code example of how this class simplifies the way in which a developer can take advantage of the user cache.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * Get Cache Object
 */

$cacheObj = DDWinUCache::getInstance();
/**
 * Cache Data
 */

$cacheObj->set('foo', 'bar');
$cacheObj->set('bar', 'candy');
$cacheObj->set('hello_world', 'we did it!');
$cacheObj->set('apple_red_core', 'simple tagging');
/**
 * Delete Cache Entries
 */

$cacheObj->delete('*or*'); // array('apple_red_core', 'hello_world');
/**
 * Get Cached Data
 */

$cacheObj->get('foo'); // "bar"

New Features

Within this class I’ve greatly improved the functionality of the delete method. I’ve also made getting information about the user cache simpler by creating accessor methods for all user cache related data. And to top it all off I’ve implemented ArrayAccess to push the simplicity over the edge.

Improved Delete

Arguably the biggest feature of this class is the ability to delete cache entries via three methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * Traditional
 */

$cacheObj->delete('this_is_a_test_entry');
/**
 * Wild Cards '*' and '?'
 */

$cacheObj->delete('this*');
$cacheObj->delete('this?is?a?test?entry');
/**
 * Regular Expression (PCRE)
 */

$cacheObj->delete('/^this.*?entry$/i');

Accessor Methods

I’ve mapped all the data available via the arrays returned by wincache_ucahce_info() and wincache_ucahce_meminfo() into accessor methods. I’ve also added two more derived methods that can be used to help control the user cache — getMemoryUsed() and getMemoryUsedPercent()

(more…)

1

While working for a previous employer I was tasked with developing a new company “intranet” site. Changes rolled out at an aggressive rate and the process of deploying updates via FTP quickly turned into a tedious task.

After a while I decided to spend some personal time thinking of ways to make whole process a bit smoother. A few of days passed as I tossed around various ideas in my head, then it hit me…

Why not just checkout a working copy of the project onto the production server itself?

Subversion Deployement Work Flow

So simple! All I’d have to do is use the production server’s subversion client to add, update, and remove any changes — deployment becomes as simple as: $ svn up

Setting Up The Environment

As is the case with most ideas there ended up being a few issues that needed to be worked out before moving forward.

Subversion’s .svn Directories

A working copy of a subversion repository is riddled with hidden .svn directories. This is a security risk as, by default, these directories and their contents are publicly accessible. To fix this issue we need to deny access by adding the following lines of code to either the Apache Global Config file, the site’s <VirtualHost> block, or the .htaccess file in the site’s root directory.

1
2
3
4
<Directory ~ "\.svn">
    Order allow,deny
    Deny from all
</Directory>

See Apache Tips & Tricks: Deny access to some folders for more information.

(more…)