
Reflect_SetFieldByName: Generate the object by reflection and assign it by FieldByName, takes 492 nanoseconds.Reflect_Set: Generate an object through reflection, convert it to an actual object, and call the object’s fields directly for assignment, takes 73.6 nanoseconds.
Java reflection performance improvement code#
Reflection generation and acquisition of objects will add additional code instructions, and will also involve interfaceīenchmarkReflect_New-4 20000000 70.0 ns/op 48 B/op 1 allocs/opīenchmarkDirect_New-4 30000000 45.6 ns/op 48 B/op 1 allocs/opīenchmarkReflect_Set-4 20000000 73.6 ns/op 48 B/op 1 allocs/opīenchmarkReflect_SetFieldByName-4 3000000 492 ns/op 80 B/op 5 allocs/opīenchmarkReflect_SetFieldByIndex-4 20000000 111 ns/op 48 B/op 1 allocs/opīenchmarkDirect_Set-4 30000000 43.1 ns/op 48 B/op 1 allocs/opįor object creation, it takes 70 nanoseconds to generate the object through reflection, while it takes 45.6 nanoseconds to directly new the object, which is a big performance difference.įor the field assignment, there are four test cases.


The use of reflect in Java also has an impact on performance, but unlike Java reflect, Java does not distinguish between Type and Value types, so at least in Java we can pre-cache the corresponding reflect objects to reduce the impact of reflection on performance, but there is no way to pre-cache reflect in Go, because the Type type does not contain the runtime value of the object, you must go through ValueOf and runtime instance objects to get the Value object. It looks good, but we all know one thing: there is a performance cost to using reflect! Test With reflect, we can achieve the ability to get object types, object fields, object methods, get tag information of struct, dynamically create objects, whether objects implement specific interfaces, convert objects, get and set object values, call Select branches dynamically, etc.

Go reflect package provides the ability to get the type and value of an object at runtime, which can help us to abstract and simplify the code, achieve dynamic data acquisition and method invocation, improve development efficiency and readability, and make up for Go’s ability to handle data uniformly in the absence of generics.
