Re: Supporting object types in BCMath
| From: | Saki Takamachi | Date: | Mon, 18 Mar 2024 00:01:21 +0000 |
| Subject: | Re: Supporting object types in BCMath | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-122672@lists.php.net to get a copy of this message | ||
Hi,
I created a prototype, although it's pretty rough. It can overload operators and calculate not
only between
BcNum but also between BcNum and int or
string.
https://github.com/php/php-src/pull/13741
I compared the execution times.
Test code:
```
<?php
$start = microtime(true);
$num = new BcNum('3.650000001', 10);
$num2 = new BcNum('4.2335185', 10);
for ($i = 0; $i < 1000000; $i++) {
$num3 = str_repeat('1', rand(1, 1));
$num4 = str_repeat('1', rand(1, 1));
$num = $num + $num3;
$num2 = $num2 - $num4;
$num = $num + $num2;
}
var_dump('BcNum and string: ' . microtime(true) - $start);
$start = microtime(true);
$num = new BcNum('3.650000001', 10);
$num2 = new BcNum('4.2335185', 10);
for ($i = 0; $i < 1000000; $i++) {
$num3 = new BcNum(str_repeat('1', rand(1, 1)), 10);
$num4 = new BcNum(str_repeat('1', rand(1, 1)), 10);
$num = $num + $num3;
$num2 = $num2 - $num4;
$num = $num + $num2;
}
var_dump('BcNum and BcNum: ' . microtime(true) - $start);
$start = microtime(true);
$num = '3.650000001';
$num2 = '4.2335185';
for ($i = 0; $i < 1000000; $i++) {
$num3 = str_repeat('1', rand(1, 1));
$num4 = str_repeat('1', rand(1, 1));
$num = bcadd($num, $num3, 10);
$num2 = bcsub($num2, $num4, 10);
$num = bcadd($num, $num2, 10);
}
var_dump('bcadd, bcsub: ' . microtime(true) - $start);
```
Result:
```
string(33) "BcNum and string: 3.2775790691376"
string(32) "BcNum and BcNum: 4.3857049942017"
string(29) "bcadd, bcsub: 4.2680249214172"
```
The execution speed ranking does not change even if the calculation is done simply by adding one
time. When calculating between BcNum, the cost of creating an instance is probably
high. However, since this difference was obtained after 1 million trials, it may be safe to assume
that the difference is not that big.
Personally, I think the main point of this proposal is the increased convenience through operator
overloading, not execution time.
Regards.
Saki