The short answer: field_get_items() is more performant than entity_metadata_wrapper().
Check out the code for these functions:
Both require that you pass along the entity, which has already been loaded from the database. For example:
$node = node_load(123);
$items = field_get_items('node', $node, 'field_my_field_name');
print $items[0]['value'];
or, as you've already suggested:
$wrapper = entity_metadata_wrapper('node', $node);
$field = $wrapper->field_my_field_name->value();
print $field['safe_value'];
Both of these instances kind of bother me because of the silly logic in trying to get a value that's already available to you, but they are certainly useful in lots of cases.
You could just do print $node->field_my_field_name[LANGUAGE_NONE][0]['value'];
but that would throw PHP notice errors if the field doesn't have a value, since you're trying to access arrays that may not exist (i.e. [LANGUAGE_NONE][0]['value']
). I find myself doing this quite often lately:
if ($field = field_get_items('node', $node, 'field_my_field_name')) {
print $field[0]['value'];
}
which is a lot cleaner than doing:
if (isset($node->field_my_field_name[LANGUAGE_NONE]) && isset($node->field_my_field_name[LANGUAGE_NONE][0])) {
print $node->field_my_field_name[LANGUAGE_NONE][0]['value'];
}
If you look at the code for field_get_items())
you'll see that it's doing nothing more then ensuring that the field's array has data in the curent language and then returns it. So, the overhead of running such a tiny function is negligible, but if you are really concerned with performance you can just do your own check if the data exists and then print it.
Edit: Since field_get_items()
runs field_language()
there would actually be a bigger performance hit than just checking the language, so, if you already know that $entity->language exists, you could just write your own super-performant function:
function my_super_performant_field_value_getter($entity, $field_name) {
return isset($entity->{$field_name}[{$entity->language}]) ? $entity->{$field_name}[{$entity->language}] : FALSE;
}
field_view_field()
is for rendering a field. The function to get the value of a field is field_get_items().field_get_items()
incurs zero database overhead so I think that's a pretty open and shut case :)field_get_items()
incurs zero database overhead? It has to get its data somewhere, right?entity_metadata_wrapper
works, performance-wise.field_get_items()
so the overhead has already been incurred...it's a bit of a strangled route in D7 to be honest