I have a globalish variable which is $VARcurrenttime = time(); then I normally call that variable when computing anything with that timestamp (which is a lot). Someone suggested to me that using time() instead of the variable would be somewhat faster. I don't really know but could someone advise me on whether I would bother changing this or not?
This:
/* Real-World Time is 2010/01/01 12:00:00 */
$var = time(); /* $var = 2010/01/01 12:00:00 */
$a = doSomething($someOtherVar, $var); /* Passes 2010/01/01 12:00:00 */
$b = doSomething($someOtherVar, $var); /* Passes 2010/01/01 12:00:00 */
$c = doSomething($someOtherVar, $var); /* Passes 2010/01/01 12:00:00 */
/* Real-World Time is 2010/01/01 12:00:40 */
takes almost exactly the same but very-slightly less time as this:
/* Real-World Time is 2010/01/01 12:00:00 */
$a = doSomething($someOtherVar, time()); /* Passes 2010/01/01 12:00:00 */
$b = doSomething($someOtherVar, time()); /* Passes 2010/01/01 12:00:07 */
$c = doSomething($someOtherVar, time()); /* Passes 2010/01/01 12:00:23 */
/* Real-World Time is 2010/01/01 12:00:40 */
but it is also very different because even though the real-world time for both of them is about the same, one is grabbing the latest time each call. Depending on your needs this is either desirable or undesirable.
As time() has to compute something (even if it is just a system lookup) I'm going to assume it is slower than referencing a variable, but the difference is going to be so close to negligible that it is completely not worth worrying about - what is more important is do you need to use the same timestamp multiple times or the current time multiple times?
The real-world analogy is comparing writing down the time and then looking at that number everytime someone asks you "what's the time" or checking a watch. They are going to take around about the same amount of time but give very different answers.
Ultimately you are comparing the speeds of two completely different things. You are not comparing the speeds of two ways to do the same thing. It's like me asking you, which is faster - getting an aeroplane overseas or driving a car to your work. The answer is one is faster, but they do completely different things.
Your friend is wrong.
- The variable stores the result of the function, making it a straight read.
- The function has to calculate the value each time it's called, which takes longer. (The exact time required depending on what the function is doing.)