Oct 1, 2024
0
Level 1
Eloquent performance extremely slow when cast to JsonResource
I see to many calls of Illuminate\Database\Eloquent\Model::getCasts
Looks like this functions calls each time when access to any attributes and never cached.
SPX_ENABLED=1 SPX_AUTO_START=0 php artisan tinker
$devices = Device::query()->limit(157)->get();
Auth::login(SystemUser::first());
$x = DeviceListResource::collection($devices);
$x->resolve(); //Avoid n+1 request increasing time in test result
{
spx_profiler_start();
$x->resolve();
spx_profiler_stop();
}
*** SPX Report ***
Global stats:
Called functions : 8.6M
Distinct functions : 653
Wall time : 1.86s
ZE memory usage : 5.4MB
Flat profile:
Wall time | ZE memory usage |
Inc. | *Exc. | Inc. | Exc. | Called | Function
----------+----------+----------+----------+----------+----------
237.6ms | 212.5ms | 161.3MB | 161.3MB | 421.1K | Illuminate\Database\Eloquent\Model::getCasts
894.6ms | 185.7ms | 652.4KB | -57.5MB | 319.1K | Illuminate\Database\Eloquent\Model::transformModelValue
163.1ms | 104.9ms | 57.5MB | 57.5MB | 279.3K | Illuminate\Database\Eloquent\Model::getDates
64.7ms | 64.7ms | 0B | 0B | 317.7K | Illuminate\Database\Eloquent\Model::hasAttributeGetMutator
66.1ms | 59.7ms | 8.6KB | -112.8KB | 157 | Illuminate\Database\Connection::Illuminate\Database\{closure}
52.7ms | 39.3ms | 0B | 0B | 279.3K | Illuminate\Database\Eloquent\Model::usesTimestamps
188.0ms | 16.0ms | 33.4KB | 33.4KB | 38.3K | 1@Illuminate\Support\Collection::Illuminate\Support\Traits\{closure}
103.7ms | 12.0ms | 652.4KB | 0B | 31.8K | Illuminate\Database\Eloquent\Model::castAttribute
172.0ms | 10.4ms | 0B | 0B | 12.9K | data_get
96.7ms | 6.5ms | 1.3MB | 304.9KB | 157 | App\Http\Resources\System\Device\SystemBaseDeviceResource::toArray
DeviceListResource looks like this, but this is common issue, you can also use any Eloquent collection and just call ->where() to see the problem
class DeviceListResource extends JsonResource
{
public function toArray($request): array
{
return [
'serialNumber' => $this->serial_number,
...
];
}
}
Please or to participate in this conversation.