5 years ago

Eloquent performance improvements -- studly caps

Posted 5 years ago by zefman


So I have recently been experimenting with blackfire.io the profiling tool on a fairly data heavy app, and noticed that there were thousands of calls to Illuminate\Support\Str::studly which is converts a string into studly case. This is obviously pretty heavy due to the string transformations.

After a little digging I found this is used in an Eloquent Model's hasGetMutator, a function that is called whenever an attribute from a model is retrieved to check to see if you have created a mutator.

     * Determine if a get mutator exists for an attribute.
     * @param  string  $key
     * @return bool
    public function hasGetMutator($key)
        return method_exists($this, 'get'.studly_case($key).'Attribute');

In the app I'm profiling we never use get mutators ( all models pass through a dedicated transformer at some point ) so this is a complete waste. Solution? Extend the standard eloquent model and override the hasGetMutator method like so:

public function hasGetMutator($key)
    return false;

Doing just this has shaved about 400ms of my response times on the most data heavy parts of the app, sometimes more.

Can anyone see any possible unexpected side effects from doing this? Maybe it would be a good idea to be able to set a flag on the eloquent model to enable and disable this feature.

Please sign in or create an account to participate in this conversation.