Home  >  Article  >  Backend Development  >  Why is Golang reflection slow?

Why is Golang reflection slow?

angryTom
angryTomOriginal
2020-03-17 11:50:203555browse

Why is Golang reflection slow?

Why Golang reflection is slow

Golang’s reflection is very slow. This is related to its API design. In java, we generally use reflection in this way.

Field field = clazz.getField("hello"); 
field.get(obj1); 
field.get(obj2);

The obtained reflection object type is java.lang.reflect.Field. It can be reused. As long as different obj is passed in, the corresponding field on this obj can be obtained.

But Golang’s reflection is not designed like this: (Recommended learning: jquery video tutorial)

type_ := reflect.TypeOf(obj) 
field, _ := type_.FieldByName("hello")

The field object taken out here is of reflect.StructField type, but it There is no way to get the value on the corresponding object. If you want to get the value, you have to use another set of reflection for object instead of type

type_ := reflect.ValueOf(obj) 
fieldValue := type_.FieldByName("hello")

The fieldValue type taken out here is reflect.Value, which is a specific value, not a reusable one Reflection object, each reflection requires the malloc reflect.Value structure, and also involves GC.

Summary

There are two main reasons why Golang reflect is slow

1. It involves memory allocation and subsequent GC;

3. There are a large number of enumerations in the reflect implementation, that is, for loops, such as types.

For more golang knowledge, please pay attention to the golang tutorial column on the PHP Chinese website.

The above is the detailed content of Why is Golang reflection slow?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn