I would like to know about the efficiency / performance of using Laravel's new Conditional Statements when()
that comes in the Query Builder functions.
Are they more efficient than a simple variable condition?
Example: i am filtering results with some radio and checkboxes, and they will provide many conditionals, i would like to know the most efficient way of applying them:
Simple conditional:
if($request->has('sale')) $query = $query->sale();
Laravel Conditional statement:
query->when($request->has('sale'), function ($query){
return $query->sale();
})
Thanks in advance, cheers.
Docs: https://laravel.com/docs/5.2/queries#conditional-statements
TL;DR: The when
function is little more than syntactic sugar. It's not more efficient than regular conditionals, and (probably) not less efficient enough to worry about.
Let's have a look at the when
method's source code:
public function when($value, $callback)
{
$builder = $this;
if ($value) {
$builder = call_user_func($callback, $builder);
}
return $builder;
}
As you can see, the when
method does not do anything different than if (<your conditional>)
and then calling the callback function supplied by you.
Because it does exactly the same as your simple conditional example, it cannot be more efficient. It will probably be marginally less efficient, because it involves two additional method calls -- however, this will so marginal that I would not worry about any performance impact. If you're concerned about efficiency, you should profile both implementations and only optimize if it proves to be a bottleneck.
The real reason for the when
function's existence is syntactic sugar. It allows you to conditionally add new constraints to a query without breaking the QueryBuilder
's fluent interface:
$q = $q
->when(isset($foo), function() use ($foo) { return $q->where('foo', $foo); })
->when(isset($bar), function() use ($bar) { return $q->where('bar', $bar); })
->when(isset($baz), function() use ($baz) { return $q->where('baz', $baz); });
As opposed to
if (isset($foo)) {
$q = $q->where('foo', $foo);
}
if (isset($bar)) {
// ...
In certain circumstances this might prove to be better readable (or not). In the end, whether to use when()
or a simple conditional instead, is nothing more than personal taste.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With