-4

OPTION A

index.php

<?php
my_function(){
//Code of 15 lines
}

//Other Codes

echo my_function();

//Other Codes

?>

OPTION B

function.php

<?php
my_function(){
//Code of 15 lines
}
?>

index.php

<?php
required_once 'function.php';

// Other Codes

echo my_function();

//Other Codes

?>

Which option (A/B) will be fast and consume less CPU Usage? Why?

Which one is better? (required_once / include_once) Why?

Raven
  • 1
  • 1
  • Have you tried timing this yourself? Also what do you mean by *better*? – Nigel Ren Nov 16 '18 at 19:01
  • Why don't you test it and see? – miken32 Nov 16 '18 at 19:01
  • I don't know how and where to test... – Raven Nov 16 '18 at 19:03
  • Loading 1 file will always be initially faster than 2. Opcache will reduce this effect. Has nothing to do with CPU, it has to do with disk access. You should never choose to store everything in one file because it would be a nightmare to maintain, so this question means little in the grand scheme of things. – Devon Nov 16 '18 at 19:20
  • How to check? @NigelRen – Raven Nov 17 '18 at 14:50
  • If you mean performance - https://stackoverflow.com/questions/8291366/how-to-benchmark-efficiency-of-php-script – Nigel Ren Nov 17 '18 at 14:51

1 Answers1

0

The difference is too small to worry about. Instead, pick the coding pattern that works 'better' for you.

As for require vs include -- require should contain global declarations potentially shared by multiple modules. include should be snippets of code that are potentially used multiple times (even in a single module).

As for once or not -- The creator of PHP says that once is a tiny bit slower. But I suspect it is on the order of a millisecond. That is such a tiny fraction of the total time as to not be worth worrying about.

Rick James
  • 122,779
  • 10
  • 116
  • 195
  • What's your recommendation? – Raven Nov 18 '18 at 06:15
  • @Raven - In my coding, I do some of each. In general, I keep the functions in the `.php` where they are first needed. When (if) I think they might be needed by multiple modules, I move them to a `.inc` file. I worry more about how easy it is for me to edit the file(s) than runtime performance. – Rick James Nov 18 '18 at 16:54
  • @Raven - and I added comments on require/include and once. – Rick James Nov 18 '18 at 16:58