Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does using instanceof calls take so much time?

Tags:

php

I don't know why instanceof calls take so much time. For example:

if($this instanceof Player){
    // Lags the server.
}

but if I add this in the player class:

public function isPlayer(){
    return true;
}

And then do:

if($this->isPlayer()){
    //Super fast.
}

It is much faster. So, when I do if ($this instanceof Player) what is the server really doing during that time?

like image 881
Callerap Avatar asked Mar 06 '26 05:03

Callerap


1 Answers

PHP uses string comparison for instanceof checks.

If you have very long classnames or calling it very often there can be a significant slowdown. Please have a look at the Instanceof section at https://phpgoodness.wordpress.com/2010/07/23/some-php-performance-myths/, there is a performance comparison which shows the difference.

like image 145
Nico M Avatar answered Mar 08 '26 17:03

Nico M



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!