27 September 2007

Function Vs Alias in PHP


Some useful information in PHP. It will help you to choose right function and increase the speed of your php page by a bit.
1. ini_alter And ini_set

Lets look at modifying the environment. I actually cheated here and just set the max execution time to 60 seconds a million times. I think the result is still valid though

ini_alter and ini_set
ini_alter: 103.332370043 seconds
ini_set: 86.2883789539 seconds
Time saved: 17.0439910889 seconds; 19.7523598143%
2. doubleval And floatval

Both these functions allow you to quickly pick a float, or double, out of a string.

doubleval and floatval
doubleval: 4.56571412086 seconds
floatval: 4.35375285149 seconds
Time saved: 0.211961269379 seconds; 4.8684727087%

4% or 211 nanoseconds is next to nothing. I would want to use floatval but I wouldn't exactly be kicking myself if I slipped a doubleval into my code instead.
3) sizeof and count
Count = counts elements of an array.
sizeof - is an alias of count.
They can both be used to count the number of items in an array but does one do it better?
The count function was over 12% faster in this test. Both functions are fast though taking 3-4 microseconds to count an array with 100,000 items.
4. is_int and is_integer
is_int is faster than is_integer so again the shorter function name wins
5. fwrite and fputs

So far all the functions have been running fast anyway so the difference haven't been that significant but things are starting to get interesting with the run time jumping to 20-24 microseconds to write a short string to a file.

fwrite and fputs
fwrite: 24.9826359749 seconds
fputs: 20.1990799904 seconds
Time saved: 4.7835559845 seconds; 23.6820488199%

With a difference of over 4 microseconds you could run both fputs and floatval in the time it takes to run fwrite. The difference is over 23% which clearly makes fputs the better function. It's shorter as well.
6. chop and rtrim

chop and rtrim
chop: 4.73731994629 seconds
rtrim: 4.41647195816 seconds
Time saved: 0.320847988129 seconds; 7.26480301852%

rtrim is a little faster and these functions take longer at a little over 4 microseconds.

7. implode and join

Both these functions allow you to convert an array into a string. implode is the opposite of explode and join allows you to join the items in an array with a 'glue' string. In this case the array had 100 items.

implode and join
implode: 47.2712550163 seconds
join: 50.1287050247 seconds
Time saved: 2.85745000839 seconds; 5.70022705949%

5% doesn't seem like all that much but 2 microseconds shouldn't be ignored.


As might be expected these functions are expensive when it comes to execution time. That 17 microsecond saving is massive as well making ini_set the superior choice.
In general, using a non-alias function if faster than using an alias

No comments: