Although the reflection (reflect) has a performance problem, it is still used frequently to compensate for the lack of static language in dynamic behavior. Only sometimes, we have to make some modifications to improve performance.
For readability, the following examples are streamlined to the maximum extent possible.
If it's reflect. Type, which can be cached to avoid time-consuming repetitive operations. But Value is obviously not possible because it is bound to the concrete object, and the internal storage instance pointer. In other words, the field is relative to the structure, with the exception of the name, which is the only property of the offset. Performance gains can be achieved by using offsets to turn fieldbyname into a normal pointer operation.
Test the optimization results.
It works well, doesn't it? The remaining question is how to design the cache structure, which naturally cannot be used for actual development.
With Map[type]map[name]offset? Obviously not. Execute reflect every time. TypeOf, this is detrimental to performance optimization. What else can I use as a Key, except for Type? You know, the interface is composed of itab and data pointers, the same type (interface and actual type combination) of the itab pointer is the same, nature can also be used as a key.
Although performance has declined due to the introduction of a map, it has improved a lot compared to direct use of reflect.
Performance optimizations using pointer type conversions, which are "very means", are a way of abandoning "other" for performance. Rather than worrying about whether your code will adapt to future changes, write a unit test to make sure that you make the necessary security checks when you upgrade. Also, this optimization series, only provides an optimization idea, not necessarily copied.
Latest news, please scan the code attention
Go Performance Optimization Tips 8/10