PHP include inside loop - is it hard on disk io?

Im working on a website that shows products. The site is written in PHP.

to make it easier to maintain, I created a php code for the "product" item with thumbnail, price, etc.

I would like to know if it is hard on Disk IO to put an include file inside a foreach. Let say the array counts about 200 items.

foreach($wines AS $wine):
    require 'components/wine.php';
endforeach;

Are we still ok or there will have some hosting issue?

Thanks!

1 answer

  • answered 2021-11-29 04:54 Daniel Cruz

    Answer

    Regarding your question though, its probably Ok with the disk. Files imported using require() are also cached in precompiled bytecode the same way as the main file (if you have OPCache or any cache system enabled), so PHP wont read it from disk every time you include it.

    Recomendation

    I would not recommend that approach at all. I think a more recomendable approach would be to define a function that returns or displays whatever you want to show, then require the file once and call the function between the loop.

    I see many downsides in your approach, like:

    1. Its a bad practice, it couples your code because now this file can only be included in this file. It becomes required that the contents of the file are aware of the file that its including it, making it harder to maintain and more prone to errors in the future.
    2. It can arise problems in the future, eg. if someone declares a function inside the file, it would cause a crash as requiring the file twice would redeclare the function leading to an error
    3. It will cause some overhead in the execution, as PHP perform some validations and operations when a file is included

    If you want more information about require or OPCache I link documentation below

    https://www.php.net/manual/en/function.include.php https://www.php.net/manual/en/intro.opcache.php

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum