We are going to start by running some test cases. These test cases are going to be kept simple, since the main point of this "experiment" is to truly get the gist of how much overhead there really is when using classes. Obviously, this is not a true object oriented program, but the use of classes contribute quite a bit, and is just enough to get an idea of how efficient OOP is in PHP.
Here is the code we are going to use for our first test case:
| OOP | Function | Neither |
| class test { function one() { return 1; } } $testclass=new test(); } |
function one() { return 1; } $cnt+=one(); } |
for ($i=0; $i<1000000; $i++) { $cnt+=1; } |
Here are the execution times for the code given above. We ran
through each snippet of code 10 times to get a more accurate result.
First test case (in seconds)
|
|
* These tests were run on a Dual Xeon 2.0Ghz
(using hyper-threading) with 2GB RAM.
As we can see, using just functions are approximately 288% faster,
and using neither functions nor classes are 486% faster in this test
case. From this test case, we can see that using classes for simple
tasks end up being very inefficient.
Here is the code we are going to use for our second test case:
| OOP | Function | Neither |
| class test { function one() return 1; } } $testclass=new test(); } |
function one() { return 1; } $cnt+=one(); } |
for ($i=0; $i<100000; $i++) { $cnt+=1; } |
Basically, the main difference between the first test case code and
the second test case is that we are simulating 10 functions being
executed at once instead of just one. This may decrease the time for
the OOP results due to the fact that the class only has to be
initialized once for every 10 function calls, instead of on every
function call.
Here are the execution times for the second test case, once again,
we ran through each snippet 10 times for more accurate results.
Second test case (in seconds)
|
|
* These tests were run on a Dual Xeon 2.0Ghz
(using hyper-threading) with 2GB RAM.
In the second test case, we see OOP being more efficient, and the
difference between OOP and functions is not as great as in the first
test case. In this test case, functions are approximately 208%
faster, and using neither functions nor classes are 635% faster.
From our two quick test cases, we see that using OOP in PHP can be
considerably slower. But just because it is slower, does not mean we
should stop writing OOP code all together, but instead, we should
consider the function approach for pages that tend to get a large
number of hits per day. It is also possible to use neither, but
really, do we want to maintain code that does not use functions at
all?
Therefore, the next time you are developing PHP code, you should
consider whether you want faster execution times / less CPU load, or
easier to maintain code.
