PHP: A case for Zephir

Zephir is an open source, high-level language designed to ease the creation and maintainability of extensions for PHP, with a focus on type and memory safety.

(Ze)ndEngine / (P)HP / (I)nte(r)mediate

Zephir is a language that addresses the major needs of a PHP developer trying to write and compile code that can be executed by PHP. For all intents and purposes, it’s a transpiler that allows you to write code in a custom “Zephir” language that compiles down to C++.

Installation

The installation docs will suggest using Composer however, I’ve found it easier to compile from source.

$ brew install re2c
$ git clone git@github.com:phalcon/zephir.git
$ cd zephir && ./install -c
$ zephir help

Some basics

There are some basic details to remember when writing Zephir code:

  • No opening tag/line (<?php, <?, etc.)
  • Defining a property value will make it immutable, define initial values in the __construct method if you expect values to change
  • Methods support parameter as well as return type-hinting
  • Using string, array, int type hints for parameters makes them immutable, use var if the values will change
  • There is a Sublime Text syntax highlighter available
  • String values are defined using “double-quotes”, not single-quotes
  • Defining/updating variables is done using the let keyword (let variable = "value")
  • You cannot (currently) create classes in the Global Space

Findings

In this case, a custom version of the library/Zend/Registry.php file was deployed.

The below graphic is of two XHProf snapshots taken from a Zend Framework 1 (ZF1) application. The first is with our custom Zephir Zend\Registry; the second is of the existing stock PHP ZF1 Zend_Registry.

Perhaps the most important stat to observe is Incl. Wall Time (microsec). At ~7k calls, the stock Zend_Registry takes ~197 milliseconds. Our custom Zend\Registry reduced the PHP time spent in retrieving registry items from to 95ms. As expected, the CPU load is also reduced by half.

Our Zephir equivalent executes 53% faster than the stock Zend_Registry.

Resources


Originally published at seanwragg.com on January 6, 2016.

Show your support

Clapping shows how much you appreciated Sean Wragg’s story.