1
0
mirror of https://github.com/php/php-src.git synced 2026-03-24 00:02:20 +01:00

Improve performance of intval('+0b...', 2) and intval('0b...', 2)

For this benchmark:
```php
<?php

for ($i = 0; $i < 10000000; $i++) {
    intval('+0b11111111111100000000', 2);
}
```

On an i7-4790:
```
Benchmark 1: ./sapi/cli/php x.php
  Time (mean ± σ):     527.3 ms ±   8.1 ms    [User: 523.5 ms, System: 2.4 ms]
  Range (min … max):   515.4 ms … 545.1 ms    10 runs

Benchmark 2: ./sapi/cli/php_old x.php
  Time (mean ± σ):     629.3 ms ±   6.0 ms    [User: 625.9 ms, System: 1.8 ms]
  Range (min … max):   622.8 ms … 643.2 ms    10 runs

Summary
  ./sapi/cli/php x.php ran
    1.19 ± 0.02 times faster than ./sapi/cli/php_old x.php
```

Closes GH-20357.
This commit is contained in:
Niels Dossche
2025-11-02 11:32:33 +01:00
parent 5ab594cf01
commit 0af87e9703
2 changed files with 8 additions and 4 deletions

View File

@@ -127,3 +127,4 @@ PHP 8.6 UPGRADE NOTES
. Improved performance of array_fill_keys().
. Improved performance of array_unshift().
. Improved performance of array_walk().
. Improved performance of intval('+0b...', 2) and intval('0b...', 2).

View File

@@ -173,14 +173,17 @@ PHP_FUNCTION(intval)
}
if (strval[offset] == '0' && (strval[offset + 1] == 'b' || strval[offset + 1] == 'B')) {
if (strval[0] != '-') {
/* Either "+0b", or "0b" */
RETURN_LONG(ZEND_STRTOL(strval + 2 + offset, NULL, 2));
}
char *tmpval;
strlen -= 2; /* Removing "0b" */
tmpval = emalloc(strlen + 1);
/* Place the unary symbol at pos 0 if there was one */
if (offset) {
tmpval[0] = strval[0];
}
/* Place the unary symbol at pos 0 */
tmpval[0] = '-';
/* Copy the data from after "0b" to the end of the buffer */
memcpy(tmpval + offset, strval + offset + 2, strlen - offset);