Reputation: 53
Wanna ask if somebody has been used PHP and Firebase together using this library: https://firebase-php.readthedocs.io/en/latest/
For some reason every single key from firebase take a long time to get out. Each item around 700-800ms. 10 Items about 8 seconds, etc. Why it's so slow?
foreach ($data as $key => $value){
$this->database->getReference()->getChild($this->dbname)->getChild($userID)->getValue();
}
This loop can take for ever if in object there is 100 items. Why it's so slow and how I can fix it?
Upvotes: 0
Views: 1414
Reputation: 162
Fastest way to reduce the runtime is by getting snapshot of the complete database.
This is the hierarchy of database looks like
Database hierarchy in firebase
Below is the basic code to retrieve the data using custom function downloadDatabase();
require __DIR__.'/vendor/autoload.php';
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
class accountInfo{
protected $database;
protected $dbname = "users";
public function __construct(){
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/secret/yoursecret.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
$this->database = $firebase->getDatabase();
}
public function downloadDatabase(){
return $this->database->getReference($this->dbname)->getValue();
}
}
$users = new accountInfo();
$array = $users->downloadDatabase();
Now you have your $array with complete database snapshot. You can easily display all the data neatly by using foreach loop.
foreach ($array as $key => $value) {
echo $key."<br>";
if(is_array($value)){
$value2 = $value;
foreach ($value2 as $key2 => $value2) {
echo "----";
echo $key2." : ".$value2."<br>";
}
}
echo "<hr>";
}
To test the speed of your code use this at the beginning of your code.
$start = microtime(true);
and then at the end of your document use this
$time_elapsed_in_microsecs = microtime(true) - $start;
echo "<hr>Runtime : ".$time_elapsed_in_microsecs;
Upvotes: 0
Reputation: 599131
Reading data from Firebase in this way, these are the main factors that affect performance:
This in total apparently 700ms for each item. There is no magic switch that will make this go faster, you will either have to ask less from the database or do it in fewer calls.
The most common ways to improve performance:
Upvotes: 1