HashTable* wrap, classes zpp::htab_*
C++ classes of an extension will be transferring data to and from zend_objects and zend_arrays.
Behind the PHP array class is the zend_array structure, HashTable. This is storage structure of considerable sophistication, and for most purposes is a set and fetch store of zval structures, indexed either by string hash, or by integer indexes.
HashTable manipulation is mediated in the limit by a large family of zend C API functions. Not all of them are needed, and the most useful are hidden inside ZPP C++ classes of htab_* which wrap a HashTable* with simple access methods. The HashTable has a problematic behaviour, in that shares access, just like all the other zend data handle types, with each share adding to its reference count. These shares only allow for read access, as any attempt to alter the contents of the array, in a shared state, lead to an automatic duplication, known as a "copy on write" operation - COW.
From the limited experiences in using zend array API calls, the cow operation is not implemented in the low level API functions to attempt the array update, as these don't have access to context the particular HashTable* is bound to. Update calls will just fail without an exception. Their is a bit flag that can be temporarily set to override this, but this really feels like a cheat, and kind of breaks the COW contract.
Because of its nature, the COW is a process that can only be done at a higher level by the caller before an array update attempt.
Zend objects do not have this feature, as multiple variables can share access to an object and all share access to updates to its object properties.
To implement COW behaviour in the ZPP framework, only one of the wrapper classes, the htab_cow, has the additional methods which which to update the contents of a HashTable* in some way, by an insert, update or delete. The htab_ptr and htab_rc wrappers have "read-only" methods. In order to simplify its update methods, the COW operation is performed only and entirely by the htab_cow constructor, and the "owner" of the new writeable HashTable* is the donating class wrapper. The "owner" reference can be one of { htab_rc, val_rc, val_ptr, or zval* }. If for some reason, the COW duplication is not wanted to be shared until write operations are actually done, the share can be done to another htab_rc in advance, and only restored to an original owning zval, when completed as a batch. However the ZPP framework classes have not been so coded as to employ this extra polite nicety in practise, and have handed their context to htab_cow directly before so the array handle split.
The cow operation is done in a protected static method of htab_cow, (htab_cow::cowop) which calls the zend API function zend_array_dup(HashTable*), to do the internal work that the zend API hides.
htab_ptr
- Is constructed by passing it a valid HashTable*.
- Does not change HashTable reference count
- Has many functions to read values from its wrapped HashTable*
htab_rc
- Inherits all its read methods from htab_ptr.
- Expresses ownership by changing the HashTable* reference count
htab_cow
- Constructor does Copy on Write of the HashTable* value, if required to give reference count of 1.
- If COW is performed the new value is still managed by the donator class.
- Inherits all read methods from htab_ptr.
- Methods that out all writes andupdate functions on the HashTable*.
This is a self-reminder that the source currently has very little in the way of code comments to explain how,why, what of various methods.
htab_ptr
constructors
htab_ptr gets its only data member a HashTable* , from any other wrapper class that might have one. The default constructor assigns a nullptr. This means a bool isNull() method exists to check that. In practise also useful are the ok() method and size() methods which check for a wrapped nullptr.
htab_ptr alsays assumes some other class is managing the HashTable* reference count,
- A bare HashTable*
- val_rc class
- val_ptr class
- zval* pointer, in function call
- Another htab_ptr class.
htab_ptr() : ht_(nullptr) {}
htab_ptr() : ht_(nullptr) {}
htab_ptr(const htab_ptr& rc) : ht_(rc.ht_) {}
htab_ptr(HashTable* ht);
htab_ptr(const val_rc& zw);
htab_ptr(zval* p);
Has an assignment operator= from a zval*.
Pointer passing
Like all the zpp *_ptr wrapper classes, htab_ptr has a cast-operator () to its wrapped Hashtable*. Also a ptr() method to return it. This makes it easier to tell the C++ compiler to pass the zend pointer type to zend API functions.
There is no isset method, other than for val_ptr
The method isset is only found in val_ptr, to indicate it contains some type other than IS_UNDEF or IS_NULL. The function isset() is a special PHP script function, applied to zval variable, or array index or property in a script. ZPP htab_*, str_* and obj_* are at a lower level than this. (is at a lower level than this. Methods has_index, and has_key are provided for htab_*, and has_property for obj_*.
bool has_index(zend_long key);
bool has_key(zend_string* skey);
// It is assumed zval_ptr has a zend_string , or zend_long value.
bool has_key(zval_ptr skey);
Get or Array operator
The array operator calls the equivalent get function to do the job. The get methods were done first, and operator[] added for cuteness. They all return a zval*, since this is what the zend API functions return.
zval* get(zend_long idx) const;
zval* get(zval_ptr key) const;
zval* get(zend_string* zkey) const;
//...etc
try and fetch
All of these return a bool (true or false) for the success of the lookup and assign on success operation. There are a few more, like this. Note that none of this arguments for string key use any kind of reference to a zstr_ptr or zstr_own class, because C++ will automatically use their cast operator to push a zend_string*.
bool try_fetch(zval_own& key, zval_ptr& store);
bool try_fetch(zend_string* key, zval_own& store);
bool try_fetch(zend_string* key, zval_ptr& store);
//...
Read methods
The htab_* read functions all return a zval* for read operations, as it is very easy to pass on value returned from zend array API calls. There are a few inline operator[] functions, which just call the objects get method with the same argument. All the handle wrapper classes have constructor and assignment operator methods which take a zval* and try to assign to their own wrapped type. If this fails, because the zval* does not contain their handle type to be assigned, they essentially become a nullptr.
// not inlined at present
zval*
htab_ptr::get(zend_long idx) const
{
zval* result = (ht_) : zend_hash_index_find(ht_, idx) : nullptr;
return result;
}
// not inlined at present
zval*
htab_ptr::get(zend_string* zkey) const
{
//showstr("::get zkey", zkey);
zval* result = (ht_) ? zend_hash_find(ht_, zkey) : nullptr;
return result;
}
zval*
htab_ptr::get(zend_string* zkey) const
{
//showstr("::get zkey", zkey);
zval* result = nullptr;
if (ht_) {
result = zend_hash_find(ht_, zkey);
}
return result;
}
// inline operators
zval* operator[](zend_long idx) const { return get(idx); }
zval* operator[](zend_string* zkey) const { return get(zkey); }
The get functions return a nullptr into the zval_ptr class, if the key does not find a stored value.
htab_rc - taking ownership
The most important part of htab_rc is that it "is - a" htab_ptr, with non-virtual inheritance, and has an internal methods own() and lose(), which manage the reference count of its wrapped HashTable* value. Most of its operators are concerned with calling these as appropriate with construction, assignment and move operations.
htab_cow array modify methods
Packed array with push_back
// Append string value, or zval* with anything, to next free integer index.
void push_back(zend_string* zs);
void push_back(const char* s, std::size_t slen);
void push_back(zval* zv);
Set or Unset methods
There are a combinatorial number of these, with different ways to pass a string key, and a value source. Almost N^2^. There are far many more zend API C functions for setting an array value. They are all called set. Another version was added every time the need was felt. Unset at least only needs one argument.
void set(zend_string* key, zval* val);
void set(zend_long idx, zval_own& value);
//...etc
bool unset(zend_long idx);
bool unset(zend_string* key);
bool unset(zval_own& key);
void unset(zval_ptr key);
Special assign to zval* return_value in PHP object method implementation.
Even though the htab_ptr doesn't care about reference counts, this is the one exception. When returning an array, from inside a PHP object method, as the method "return_value" parameter zval*, PHP handle types need to be given an appropriate reference count. Return values from C++ methods which are of type *_ptr call their own method of copy_zv(zval*), to pass on their array handle reference before the stack frame existance disappears.
This might make the API complain if another attempt to write to the HashTable is made. Due to copy-on-write practices for zend_array, warnings or exceptions will happen if its reference count is greater than 1. PHP normally ensures this by making a copy on write, but the above functions do not do this, and successful updates depend on (HashTable* reference count == 1).
void htab_ptr::copy_zv(zval* return_value) const
{
// Protected class method of friend htab_ptr,.
// Bump array reference count.
val_ptr(return_value).bind_array(ht_);
}
void htab_rc::move_zv(zval* return_value)
{
// Protected class method of friend htab_rc.
// Transfer array pointer and forget.
val_ptr::array_bind(return_value, ht_);
ht_ = nullptr;
}
Zend value as a black box
Several important zval types, implemented by reference counted handles in particular zend_string, zend_object, zend_array, zend_reference, hold a pointer to a common part of zend handle structure that starts with a small structure type.
zend_refcounted_h gc;
The zval structure, is still ubiquitous in PHP, because its a union type, can hold any one type at a time. That means an all-purpose zval C++ wrapper, if it tries have all methods for every possible type it could hold, will be tremendously over-burdened.
This is the case in the PHP-CPP framework. Php::Value type is its general purpose zval wrapper. It has methods galore to do every kind of overloadable method operator. Php::Array and Php::Object classes, add a few specializations, but must pretend to be nothing else. Php::Value also are a number of return values of C++ STL datatypes. The current version of Php::Value also inherits a virtual function table pointer, which adds to its storage cost.
In the PHP-CPP source there is an internal String class for allocating zend_string values, defined in zend/string.h. This is specialized for generating persistant zend_string values, with permanent storage in non-request allocated memory.
On the whole the PHP-CPP either expects programmers to work with raw zend API for its reference counted types, or to be using C++ data and STL types outside of the Value wrapper. Depending on what the extension is for, minimizing the time working with the Value abstraction, and minizing callbacks to PHP script-land, is a goal. Working too much with the Value abstraction of a zval, and PHP callbacks are therefore labelled as inefficient for those expecting some performance gains from a compiled C++ extension. There is truth in this, given the ease of script programming versus time spent coding C++ extensions.
In order to set a PHP array value via C++, the plain set method is the most direct. For example, for zend_string key, htab_cow can write a zval* update to an array. There are similar set methods for all the other likely types as well.
void htab_cow::set(zend_string* key, zval* val)
{
if (zend_hash_update(ht_, key, val))
{
//Trust that val holds correct reference count flags.
if (Z_TYPE_FLAGS_P(val) != 0) {
val_ptr::try_addref(val);
}
}
}
void htab_cow::set(zend_long idx, zval* value)
{
if (zend_hash_index_update(ht_, idx, value))
{
if (Z_TYPE_FLAGS_P(value) != 0)
{
val_ptr::try_addref(value);
}
}
}
The zend_hash_update function does either an add or update function, and returns a pointer to the actual zval structure as where the data has been stored. Here it is thrown away after the non-null check. It is assumed to point to the same data as the val argument. There is no check for a non-null val argument here. It is a responsibility of the calling code to source valid value pointers.
The implementation of zend_hash_upate will copy zval contents using the ZVAL_COPY_VALUE macro. This will not add to a reference count. If it returns a non-null value, the add or update to the HashTable has been successful and the caller must see to the reference count.
The zend API has a wide variety of additional array manipulation methods, which have been ignored.
The C++ brackets assignment operator works well where the storage already exists prior to the method call, as in fixed arrays and matrices. In PHP the storage in the HashTable does not exist until the zend_hash_update returns the pointer to it, and has already updated it once. There is nothing I know in the design of C++ that easily rewrites a r-value to brackets l-value assignment, as a simple call to our set function, that already does the job.
PHP-CPP HashMember virtual function call chain
Have I missed something with this split of read (htab_ptr, read and reference count (htab_rc) and copy-on-write without reference count (htab_cow) split of methods? Early on in trying to understand PHP-CPP framework, I tried to understand why it so insists on how it uses the C++ array operators.
The design of the PHP-CPP array brackets operator of Php::Value returns a structure template called HashMember. This seemed a complexity to make the operators work as expected, for use in both read and update functions. In actual code, the Php::Value objects use the operator[] for read and write for keyed array and also object property values.
These operators work their magic via returning a templated HashMember structure, which has a base class mostly virtual functions. The parent class is HashParent, and Php::Value itself virtually inherits from HashParent. So a call to set via operator[] chain calls a virtual method of Value to call set, which will call setRaw. HashMember has many C++ style override operators.
I could not find an actual usage of the zend API function zend_hash_update anywhere in the PHP-CPP code. But there are many other zend array access and update functions to choose from.
For the write operator[], in PHP_CPP, the PHP::Value returns a HashMember structure, containing a pointer to itself, and the value of the key for the intended write. This structure has assignment operator access for whatever type of value is being assigned, and the assignment operator calls back the Value class to do the actual array update operation. This work may be to overcome limitations encountered with the C++ operator[].
So in PHP-CPP the final HashTable write calls are routed into Value::setRaw(), which is overridden with either and integer or string key. The string version calls add_assoc_zval_ex, which calls zend_symtable_str_update. This function checks if a string key is numeric, and will convert such to a zend_long index. The htab_cow::set methods do not do this check for numeric types of string keys. Functions are called according to C++ overloaded function type signature mangled names.
The PHP-CPP code is educational, for the virtuosity lengths it has gone to code PHP api manipulation as simplified Php::Value syntax. in set of classes.
The ZPP approach is to go lower level, and use PHP pointer handles directly, each with their specialized wrapper methods.
// In php-src (zend_hash.c) , is found the function called by Php::Value::setRaw(const char* key ...)
static zend_always_inline zval *zend_symtable_str_update(HashTable *ht, const char *str, size_t len, zval *pData)
{
zend_ulong idx;
if (ZEND_HANDLE_NUMERIC_STR(str, len, idx)) {
return zend_hash_index_update(ht, idx, pData);
} else {
return zend_hash_str_update(ht, str, len, pData);
}
}
This is only a vague discriptions of the HashMember call chain for array[] notation, and property access It seems that there is some additional complexity cost overhead, requiring additional class creation, and destruction, in terms of function calls. The Php::Value class a kind of swiss army knife of PHP values access. It is versitile. In memory cost, also Value instance holds a hidden virtual function table pointer, as well as a full zval structure. Value harbours a lingering identity crisis, and must often check its zval structure every time to figure out just what it really is, and what any operator function needs to do.
Old performance comparison for PHP-CPP and Wcc vs PHP script
I designed a simple XML file format for use as configuation files, with similar aims to JSON, and YAML. For this simple parser script called xmlread.php has a xmlreader class to pull-parse the format into its final hierarchy of array values including objects.
This was done for a similar algorithm using PHP actual XmlReader extension class for the actual low level parsing. The test example data files was the same for each of a PHP script reader class, a PHP-CPP extension class version of doing the same thing, and an extension class made from the C++ many zpp PHP primative types we are documenting here.
I made a PHP-CPP extension object of the read classversion, and a Wcc version, of the same class, with no major algorithm differences, however the source code classes are different. All three give the same data output values. To average better, a test script repeated the file read 1,000 times. The C++ extensions managed this timed task at least 5 times faster.
The results on this AMD Ryzen 5 laptop were :- PHP Script - 0.25 seconds PHP-CPP - 0.048 seconds. Wcc - 0.036 seconds.
The xmlread class versions all made the same PHP xmlreader object method calls, such as to read the current node string value, fetch a node attribute value, and read current property values.
Both PHP-CPP and Wcc make use of the main callback facility for the Zend API, which is call_user_fn. Just a little deeper into the API it calls the function.
zend_result zend_call_function(zend_fcall_info *fci, zend_fcall_info_cache *fci_cache)
Some slight improvement ( 1-2%) in performance was obtained by actually caching the call information in these function call cache structures, for reuse in C++ class objects. The Wcc value was 0.37-0.38 before the code was changed to use fcall_info_cache for some method calls. A current version of the class embeds a fast C++ xml parser, TinyXml2, to bypass working with the XmlReader extension object.
Since my test script, OS, PHP versions, and ZPP code, and even the neglected PHP-CPP version have been grindingly updated over a number of years, I no longer trust the exact circumstances or validity of running such a comparison. Background tasks that periodically run can influence the results by 50-100%.
If the zpp extensions are disabled, and xdebug is disabled, the performance table with a few repeats, this very hour looks like this table. Notice how having XDebug enabled is like leaving the handbrake on for the script version, but has little effect on the TinyXml2 effort. There isn't a currently compile PHPCPP version with test extension setup here right now.
Version |
best ms/it. | worst ms/it. |
|---|---|---|
| PHP Script no xdebug | 0.189 | 0.424 |
| PHP Script xdebug | 0.471 | 1.102 |
| Wcc TinyXml2 + xdebug | 0.092 | 0.208 |
| Wcc TinyXml2 no xdebug | 0.088 | 0.201 |