2

I want my Drupal site be as fast as it can. So I'm considering whether to use hook_form_alter with an if statement inside or hook_form_FORM_ID_alter. I know that it's a bit more convenient to use the latter but I'd prefer to use the faster method.

Does somebody know which is faster and how much? And I don't only mean form_alter, but all hooks with an ID in it.

1
  • 6
    Hook implementations are cached, so it really doesn't make a difference. When that cache is rebuilt, every module is tested for every version of hook_form_alter AND hook_form_FORM_ID_alter anyway, so technically you can save a bit of time (microseconds) by lumping everything for one module into a single form_alter hook. But then when that's invoked, you have to check the form ID anyway, which is another OP, and that happens at 'runtime' (no cache). Benchmark that difference if you really care, but you're in classic premature optimisation mode here :)
    – Clive
    Commented Jun 9, 2016 at 8:57

1 Answer 1

1

The hook_form_FORM_ID_alter is faster than hook_form_alter.

Modules can implement hook_form_FORM_ID_alter() to modify a specific form, rather than implementing hook_form_alter() and checking the form ID, or using long switch statements to alter multiple forms.

Form alter hooks are called in the following order:

  1. hook_form_alter()
  2. hook_form_BASE_FORM_ID_alter()
  3. hook_form_FORM_ID_alter()

I hope this helps :)

1
  • Thank you for the answer, but you just declared which option would be the faster without giving explanation why. How do you refer t Clive's comment who states that it would be hook_form_alter that would be faster?
    – user1
    Commented Jun 9, 2016 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.