Skip to content

Instantly share code, notes, and snippets.

@ishukshin
Last active May 30, 2018 20:31
Show Gist options
  • Save ishukshin/8429e88b234490ebda311ed75889179e to your computer and use it in GitHub Desktop.
Save ishukshin/8429e88b234490ebda311ed75889179e to your computer and use it in GitHub Desktop.
Testing of different methods of appending data to a json file
<?php
...
private function _appendJson($file, $data, $first = false) {
$fd = fopen($file, 'r+');
fseek($fd, -1, SEEK_END);
fwrite($fd, ($first ? '' : ',') . json_encode($data) . ']');
fclose($fd);
}
// wrong file format. Just measuring speed
private function _appendFile($file, $data, $first = false) {
File::append($file, ($first ? '' : ',') . json_encode($data));
}
private function _appendSubstr($file, $data, $first = false) {
$fs = file_get_contents($file);
$cts = substr($fs, 0, -1) . ($first ? '' : ',') . json_encode($data) . "]";
file_put_contents($file, $cts);
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info("Testing ");
$data = explode(",", '1527411080,27.11:00:20,,847,126,712,0,0,0,1,0.732');
$file = Storage::path('test.json');
foreach(['_appendFile', '_appendJson', '_appendSubstr'] as $method) {
File::put($file, '[]');
$s = microtime(true);
for($ax = 0; $ax < 1000; $ax++) {
$this->$method($file, $data, !$ax);
}
$t = round(microtime(true) - $s, 3);
$f = round(1000 / $t);
$this->info("done $method with $f appends per second");
}
}
Testing
done _appendFile with 33333 appends per second
done _appendJson with 38462 appends per second
done _appendSubstr with 3484 appends per second
Actually it was obviously, that fseek is the fastest method.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment