renfordt / clamp
Adds the support of the method clamp() for PHP.
Installs: 2 824
Dependents: 2
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^8.1
Requires (Dev)
- phpunit/phpunit: ^10.5
README
Adds the support of the mathematical method clamp() for PHP.
Installation
The recommended way of installing Larvatar is to use Composer. Run the following command to install it to you project:
composer require renfordt/clamp
Usage
The usage is very simple and comparable to the C++ function:
clamp( $value, // The value to be clamped $min, // The minimum value to clamp to $max // The maximum value to clamp to );
Alternatively you can use clampMinMax()
which is a bit slower.
clampMinMax( $value, // The value to be clamped $min, // The minimum value to clamp to $max // The maximum value to clamp to );
Why another package?
Even though there are some similar packages, this one focuses on different approaches.
First of all the syntax is similar to c++ clamp function.
Secondly and more important this package focuses on performance. Other packages uses the max($min, min($max, $num))
approach but this packages works with the following code:
if ($value > $max) { return $max; } elseif ($value < $min) { return $min; } return $value;
Even though the readability is a bit worse, the performance is up to 2x faster. In most cases this is not noticeable but in some cases there will be a benefit.
Over a iteration of 100.000 executions the functions need the following times:
String
- clamp: 0.0035040378570557 sec
- clampMinMax: 0.0061681270599365 sec
Integer
- clamp: 0.0029380321502686 sec
- clampMinMax: 0.0056021213531494 sec
Float
- clamp: 0.0028560161590576 sec
- clampMinMax: 0.0062460899353027 sec