[php-src] PR #11543: Avoid allocations when getting content of DOM nodes if possible
| From: | nielsdos | Date: | Mon, 26 Jun 2023 20:20:52 +0000 |
| Subject: | [php-src] PR #11543: Avoid allocations when getting content of DOM nodes if possible | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-22832@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/11543
Author: nielsdos
Everytime text content or node value or something alike is requested, it currently allocates memory
*twice*: once in getting the data from libxml2, and then allocating a zend_string to copy the data
into.
We can very often skip the first allocation. Let's do that because it's actually quite
common to get the
textContent for example from a node when processing documents.
Here's a microbenchmark with time measurements (only for textContent, but for nodeValue etc the
result is similar).
There's no noticeable slowdown because of the extra checks for the cases where we cannot avoid
an allocation.
Based on these results I'd say it's worth it:
```php
<?php
$doc = new DOMDocument;
$doc->loadXML('<?xml version="1.0"?><div/>');
$doc->documentElement->append(str_repeat('hello world', 10));
$el = $doc->documentElement->firstChild;
for ($i = 0; $i < 1000000; $i++) {
$el->textContent;
}
```
Bench results:
```
Benchmark 1: ./sapi/cli/php dom.php
Time (mean ± σ): 43.1 ms ± 2.2 ms [User: 40.4 ms, System: 2.6 ms]
Range (min … max): 40.3 ms … 51.5 ms 62 runs
Benchmark 2: ./sapi/cli/php_old dom.php
Time (mean ± σ): 107.6 ms ± 1.6 ms [User: 104.5 ms, System: 2.9 ms]
Range (min … max): 105.4 ms … 112.1 ms 27 runs
Summary
./sapi/cli/php dom.php ran
2.50 ± 0.13 times faster than ./sapi/cli/php_old dom.php
```