Performance
Implementation
clamp() uses direct comparisons:
if ($value > $max) {
return $max;
} elseif ($value < $min) {
return $min;
}
return $value;
clampMinMax() uses the common alternative:
return max($min, min($max, $value));
The direct-comparison approach avoids the overhead of two function calls, which makes a measurable difference at high call volumes.
Benchmarks
Measured over 100,000 executions:
| Type | clamp() | clampMinMax() |
|---|---|---|
| String | 0.00350 s | 0.00617 s |
| Integer | 0.00294 s | 0.00560 s |
| Float | 0.00286 s | 0.00625 s |
clamp() is roughly 2× faster across all types. In most applications this difference is negligible, but it matters in tight loops with a large number of calls.
Comparison with other packages
Most existing PHP clamp packages use the max/min idiom. This package uses direct comparisons to reduce function-call overhead. The syntax also matches C++'s std::clamp, which keeps the argument order consistent if you work across languages.