They perform different tasks.
drupal_static()
only stores data for the current page load (or ajax load). For example, if you are loading something from a database table multiple times on a single page load (ie - a user account), the first time it is loaded it is saved to memory, and the next time it is needed, it is pulled from memory, rather than reloading it from the database, saving that second database query.
Drupal::state()
saves data to the database, where it can be recovered in future requests. It's a cache of sorts.
You can actually use them in conjunction with each other as follows:
function get_some_value() {
// Instatiate the static
$value = &drupal_static(__FUNCTION__);
// Check if the value has already been set in this page load
if(is_null($value)) {
// The value has not yet been set for this page load,
// so retrieve it from the state if it exists, and if it
// does, then save that to the static
$value = \Drupal::state()->get('my_value');
// Check if the value was retrieved from the state
if(!$value) {
// The value was not retrieved from the state, so
// it needs to be generated. Below is an example
// fetching it from the database
$value = db_query('SELECT some_value FROM {some_table} WHERE some_column = :some_value', [':some_value' => 'some value'])->fetchField();
// Save it to the state for future page loads
\Drupal::state->set('my_value', $value);
}
}
// Return the value
return $value;
}
With the above code, the first time this function is hit, it will first check if the value exists in the static cache (this page load), and when it doesn't, it attempts to retrieve it from the state cache, and when it doesn't it finally generates it with a database query, saving it both to the static cache, as well as the state.
If it hits this function again on the same page load, the value will be in the static cache, so none of the internal code is needed, and the value is returned from the static cache.
On a future page load, the first time this function is hit, nothing is retrieved from the static cache, so it will pull it from the state cache. If the function is hit again on that page load, the value will be in the static cache and returned from that.
-- Edit from comments --
Note that if you use Drupal::state
as cache, you will then need to manage expiration on your own. If you nee in-memory caching, use the drupal_static cache. If you need a persistent cache, it is likely better to use \Drupal::cache
than to use Drupal::state
.