Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call function each time or create local variable

What's the best in terms of speed and performance? To call the function each time you need the value (e.g mysql_num_rows, time) or to copy the return value to a local variable and use that instead.

Example: Let's say that I call the time() function ten times to get the current time, would it be faster to use a local variable those ten times instead?

like image 203
Baversjo Avatar asked Jan 21 '26 04:01

Baversjo


2 Answers

This basically comes down to:

Does this make your code more readable? This should be your first consideration.

How expensive is the function call? Don't micro-optimize. Like if each call gets 2000 records from a database or calls a remote Web service then yes the performance of that call is significant. But a lot of the time it isn't.

Is it appropriate to store the value? By this I mean take time(), it can change between calls. This may be what you want or you may want to use the same time at several points, in which case you'd store it.

like image 113
cletus Avatar answered Jan 22 '26 16:01

cletus


Variables are definitely faster.

like image 30
too much php Avatar answered Jan 22 '26 18:01

too much php



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!