amitsolanki24_'s avatar

Calling multiple functions multiple times

Hey everyone, I have a doubt it's good to calling multiple functions inside loop?

Helper file

function getPrice()
{
return 1;
}

function totalPrice($quantity)
{ 
$per_price = getPrice();
return $per_price*$quantity;
}


function getUnicodeName($name)
{
// some code
}

controller file


foreach( $products as $product)
{
$product->unicodeName = getUnicodeName($product->name);
$product->totalPrice = getTotalPrice($product->quantity);

$data[] = getSomeData($product);
}

It is good or not to move code into multiple functions instead of writing smaller code direct or also tell me calling multiple functions does take more execution time.

0 likes
18 replies
JussiMannisto's avatar

It's completely normal.

What isn't considered good is defining lots of global helper functions. The issue is that different parts of the app may want their own getPrice() and you may run into naming conflicts. Your codebase will also become harder to understand as it grows. Here are some alternatives:

  • Local methods in your classes. You'd be calling $this->getUnicodeName() instead of the global getUnicodeName().
  • Traits. You can create a trait and add it to any class that needs those methods. For example: CalculatesPrices, or PricingTrait if you like PSR.
  • Static helper methods, e.g. PriceHelper::total(). A bit better than global functions. At least you won't have conflicting names.
1 like
Bogey's avatar

Have you considered using a resource?

php artisan make:resource ProductResource
namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'unicode_name' => getUnicodeName($this->name),
            'total_price' => getTotalPrice($this->quantity),
			'data' => getSomeData($this),
        ];
    }
}

and than in the controller

use App\Http\Resources\ProductResource;
use App\Models\Products;

$products = Products::all();
$data = ProductResource::collection($products);
foreach ($data as $product) {
    echo $product['id'];
    echo $product['name'];
    echo $product['unicode_name'];
    echo $product['total_price'];
}
1 like
amitsolanki24_'s avatar

@Bogey I 'm just asking if i calling multiple functions multiple times in a foreach does it reduce performance or not.

Bogey's avatar

@amitsolanki24_ That's fine, I don't think it'll make a huge difference on your performance. I provided you a way laravel built to do what you are doing. You may do it your way, or you may choose laravel's way to do that.

1 like
amitsolanki24_'s avatar

@gych I haven't heard about premature optimization yet.

Is it for speed optimization or resource optimization?

Snapey's avatar

Is it for speed optimization or resource optimization?

@amitsolanki24_ no it explains that you are worrying about miniscule performance optimizations before you have a performance problem. You are optimising prematurely.

1 like
amitsolanki24_'s avatar

@gych I have a doubt related to below text ##Why are PHP function calls so expensive?

https://stackoverflow.com/questions/3691625/why-are-php-function-calls-so-expensive

Snapey's avatar

@amitsolanki24_ try this as an analogy. If I drove my car in a straight line from one place to another, i might achieve 60kms average speed. But if I had to take a turn every 400 metres my average speed might be only 30 kms. So if all we had was straight roads between every location think how much faster we could drive. This is true, but not very practical. Think how much infrastructure would be duplicated to avoid junctions. Being able to take corners is a key feature of our cars and allows us to use sections of road for the route to multiple destinations.

Also consider, when you decide to use a framework like laravel, your user request runs through thousands and thousands of lines of code. The code you contribute might be less than 0.5% of the total lines executed. Why should you give it a moments thought when you are influencing only a miniscule portion of the total steps?

1 like
amitsolanki24_'s avatar

@Snapey yes I agree , you are right this is only a very short portion a code it's a neglects code

But I want to know how much my code effect the performance.

Snapey's avatar

@amitsolanki24_ then look for inefficient or unnecessary database queries. They can easily out weigh the rest of your code put together.

After that look for caching oportunities.

1 like
gych's avatar

@amitsolanki24_ That post is from 2010 and its looping 1 million times.

PHP and hardware improved a lot since then.

I ran the same test as in the post and this are the results

with function call: 0.020958185195923 seconds

without function call: 0.024065971374512 seconds

The difference is approximately 3.11 milliseconds which is nothing to worry about

1 like
Snapey's avatar

@amitsolanki24_ You could easily write a query of 3 lines that might take 20us or 50ms (2500 times slower) and from usage of your app you would never notice the difference.

Suggest installing Laravel Debugbar. This will show you where your app really spends its time.

Please or to participate in this conversation.