0

Simple question really. More or less another micro-brenchmarking question due to pure curiousity!
But, does creating a function use more resource (memory and/or CPU) in PHP?

Here's an example:

function test()
{
    return 1+1;
}

echo test();

vs.

echo 1+1;


Which also brings me to my second ponder! Would containing local variables have any impact too?

Example:

function test()
{
    $var = 1+1;
    return $var;
}
echo test();

vs.

function test()
{
    return 1+1;
}

$var = test();
echo $var;

vs.

function test()
{
    return 1+1;
}
echo test();
tfont
  • 10,891
  • 7
  • 56
  • 52
  • 2
    The answers to more memory and more resource usage for functions are yes and yes respectively, and local variables also yes and yes again.... for such simple functions as these, that's a given.... for more complex functions, you're potentially reducing the size of the code by bundling a series of repeated lines into one function, which can reduce memory – Mark Baker Mar 26 '14 at 15:51
  • 2
    short answer....yes. every line every char in a .php file increases memory and cpu usage. There is a cost to performance in every line. – Lawrence Cherone Mar 26 '14 at 15:51
  • @Loz Not really. You can have a very verbose algorithm which uses virtually no memory, or a single line which causes memory exhaustion. Size of source code !== memory usage. – deceze Mar 26 '14 at 15:52
  • Your questions is much more relevant to low-level programming languages like c/c++. And the short answer is yes, every line is increasing resource consumption – Sergey P. aka azure Mar 26 '14 at 15:58
  • 1
    For often repeated sequences of lines (not generally for single lines), it's normally sensible to bundle them into a function (or OOP method) for maintenance purposes as well as memory saving.... then if you need to make changes you only need to do so in one place in the code – Mark Baker Mar 26 '14 at 15:58
  • @MarkBaker, so if I am defining a variable that can just be returned, I am using up the memory (additional resource) rather than just calling the process? Which would be only CPU? – tfont Mar 26 '14 at 18:31
  • 1
    If you define a variable in a function, that has memory overhead from the point where you create it to the point where the function terminates, when the memory is freed. Allocating the memory for that variable, assigning a value to it, and then deallocating the memory when the function terminates are all activities that cost CPU overhead – Mark Baker Mar 26 '14 at 19:03
  • 1
    Note that worrying about these is premature micro-optimisation, and will have only add nanoseconds to execution time and limited memory overhead (unless you're assigning /very/ large strings to variables)... readability always matters more – Mark Baker Mar 26 '14 at 19:04

0 Answers0