在OOP中调用函数是否很慢还是开销? [重复]

This question already has an answer here:

I am building an application which does some heavy repetition of functions.

For instance:

$Class = new Class;
for($i; $i < 1000; $i++) {
    $Class->get_something();
}

I have read so many articles on OOP and why it is slow, but I still don't understand where exactly the "slow" part is. People keep using the world "overhead," is that loading the actual class? Once I require a class, is it now the same speed when I call function or a variable?

</div>

You are touching the very old debate between making a one large query to get your data, or looping over many smaller ones to receive them. And the answer lies in specifics of implementations. In some cases it is faster to call that one function over and over, while other times it will just kill your performance. The "overhead" from just calling a function over and over is pretty minimal, it's the "guts" of it that matter.

One thing that can be said is that you shouldn't use loads of useless getters in PHP, since it is true that it can slow down your code. Why don't you do a benchmark yourself, eg :

<?php

class test1{
    private $prop = 1;
    public function get_prop(){
        return $this->prop;
    }
}

class test2{
    public $prop = 1;
}

$t1 = microtime(true);
$obj1 = new test1();
for($i=0;$i<=1000000;$i++){
    $a = $obj1->get_prop();
}
echo 'test1, access with get_prop : '.(microtime(true) - $t1).'ms<br/>';

$t1 = microtime(true);
$obj2 = new test2();
for($i=0;$i<=1000000;$i++){
    $a = $obj2->prop;
}
echo 'test2, direct access to prop : '.(microtime(true) - $t1).'ms';

This outputs :

test1, access with get_prop : 1.7691290378571ms

test2, direct access to prop : 0.38315200805664ms

More than 4 times slower!

Other resource related to this topic. Static method seems much slower.

Performance of static methods vs. functions

It's the function call overhead, but it's negligible under normal circumstances. This applies for functions too, not just class methods. The overhead difference between class methods and functions is even more negligible.

It makes sense to avoid moving that code within a function and use inline code if you're going to run it thousands of times. Otherwise, you won't notice any performance impact.

Don't do this unless you really need to, because you'll end up with badly organized code