There is little difference and in PHP the concern should not be this. This is called micro-optimization and should be avoided until it proves absolutely necessary. If you really needed to optimize memory and speed, the first thing I would tell you is to change language. PHP is not suitable for applications that require the best optimization.
In PHP reasonable optimizations are those in which you choose the right data structure and algorithm. Do not improve small code details.
That being said, the second seems to be slightly better in performance and perhaps minimally in memory (again, reinforcement that makes no real difference). It seems to me to be more readable too (not everyone would agree). This yes is a good concern.
The third (which came later in editing) seems to be the slowest (I can’t guarantee and I won’t waste time trying to figure it out, it’s just not worth it) but it may not be. It is the shortest and simplest, most abstract. I would probably go in it after I have already learned to use the loop well. Maybe by changing the range
for string literal of the second.
If you can’t tell the difference between them, it makes no difference. And if you measure and see that one is better than another, just change a little and the result can be another. There are many variables influencing performance making it difficult to make a definitive assessment.
Give names of significant variables. You tried to give good names but did not hit the target. Use rand_id
as variable to count the loop generates confusion because it indicates that it should be something random. It seems to me that all these prefixes rand
in the names are all exaggerated because none of them keeps random things. But it’s just an opinion. I don’t know what your real intention is.
Also avoid keeping the final loop key on the last line. It is easier to identify the end when it is on a line alone. It’s nice but this is something that few programmers disagree.
I really liked your explanation @bigown on the name of the variables, these are not definitive, I created at random, so I worried on which of the three to use, to be able to improve the one that would be the most recommendable, in the case, for a slightly large application with many requests to the database and generation of many random numbers by many users at the same time, you would use the second option?
– flourigh
I think I would use the third one. Even more if it involves a bunch of data. Database is so much slower than processing this code that it will make even less difference. PHP is slow, there’s no point in optimizing your code. Not even Facebook doing micro-optimization in their PHP code (they did something much more radical :) )
– Maniero