Adds the support of the mathematical method clamp() for PHP.
The recommended way of installing Larvatar is to use Composer. Run the following command to install it to you project:
composer require renfordt/clamp
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
);
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:
- clamp: 0.0035040378570557 sec
- clampMinMax: 0.0061681270599365 sec
- clamp: 0.0029380321502686 sec
- clampMinMax: 0.0056021213531494 sec
- clamp: 0.0028560161590576 sec
- clampMinMax: 0.0062460899353027 sec