[Drupal] How to avoid the overhead of executing a database query many times in a page request

| | 1 min read

Multiple database access in a site can create overheads. There is a chance of this being adversely affecting the site performance if the size of the website is considerably large.

Consider a function that returns the details of a new product. And if we call this function in different regions of a page, the query will be executed for each function call. ie, multiple database requests are made for the same result.

We can reduce this overhead by using the static variable. Static variables can be used for caching data for the current request. For the above case, create a static variable in the function to store the database result. In the function definition which follows,check whether the static variable is set or not, If the variable is set, then the result can be immediately returned. So there is only one database access for all the calls in that page.

The following function shows the usage of static variable.



In the above function the static variable $product_details is set when the function is called. Then for the all other calls in the same request will give the data from the static variable, without a database access.

So using the static variable to keep the database result can be reused in a single request, which reduces the overhead.