Skip to content

Commit 6bf5cf9

Browse files
Merge pull request #5 from farbcodegmbh/docs/performance-considerations
[Docs]: Performance Considerations
2 parents 9421f35 + 3587ba0 commit 6bf5cf9

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

docs/pages/basic-usage.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ class UserResource extends StatefulJsonResource
6565
'id' => $this->id,
6666
'name' => $this->name,
6767
'email' => $this->whenState(State::Full, $this->email),
68-
'profile' => $this->whenStateIn([State::Full], [
68+
'profile' => $this->whenStateIn([State::Full], fn () => [
6969
'bio' => $this->bio,
7070
'avatar' => $this->avatar,
7171
'created_at' => $this->created_at,
@@ -96,6 +96,41 @@ You can also use magic methods with for cleaner syntax:
9696

9797
For a full list of available conditional methods, see the [Available Conditional Methods](reference/conditional-methods.md) reference.
9898

99+
### Performance Considerations
100+
101+
Please be aware that heavily relying on conditional methods can lead to performance implications depending on how they are utilized within your resources.
102+
103+
During the execution of `toArray`, all _directly accessed_ model attributes, model accessors and function calls **will be computed, no matter the current state of the given Stateful Resource**.
104+
105+
Here's an example of a Stateful Resource that may compute more than is needed when the state is `Minimal`:
106+
107+
```php
108+
public function toArray(): array
109+
{
110+
return [
111+
'email' => $this->email,
112+
'phone' => $this->phone,
113+
'address' => $this->unlessStateMinimal($this->address), // ⚠️ `$this->address` will always be computed although its value may not be used
114+
];
115+
}
116+
```
117+
118+
The impact for smaller resources is _minimal_, as the overhead of computing unused attributes is negligible. However, for large resources with many attributes, this may lead to performance issues.
119+
120+
But there is a way to circumvent this limitation by wrapping the value in a closure:
121+
122+
```php
123+
public function toArray(): array
124+
{
125+
return [
126+
'email' => $this->email,
127+
'phone' => $this->phone,
128+
'address' => $this->unlessStateMinimal($this->address), // [!code --]
129+
'address' => $this->unlessStateMinimal(fn () => $this->address), // ✅ `$this->address` won't be computed unless the condition is met [!code ++]
130+
];
131+
}
132+
```
133+
99134
### Manual State Access
100135

101136
If you need more complex logic than inline conditionals, you can access the resource's current state directly using the `getState()` method:

0 commit comments

Comments
 (0)