It's 7.9 (PHP 7.2.15) to 21.6 (PHP 7.3.0) times more expensive to use backtrace!
<?php
$prefix = 'cliff_thing';
/**
* Get the filter/action hook name, built from the plugin's prefix + underscore + method name.
*
* @todo Improve performance by requiring $name instead of allowing backtrace: https://3v4l.org/HBW4R
* @link https://3v4l.org/HBW4R Because it's 7.9 (PHP 7.2.15) to 21.6 (PHP 7.3.0) times more expensive to use backtrace!
* @link https://gist.github.com/cliffordp/03637a47300315017706826c07f124f8 This snippet.
*
* @param string $name Custom name if not using the calling function's name.
*
* @return string
*/
function get_hook_name( string $name = '' ) {
if ( empty( $name ) ) {
$backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
if (
! empty( $backtrace[1] )
&& ! empty( $backtrace[1]['function'] )
) {
$name = $backtrace[1]['function'];
} else {
// Yikes! But could happen if not called from within a function (unexpectedly).
$name = __FUNCTION__;
}
}
return $prefix . '_' . $name;
}