Fastest way to get the names of the fields of a ca

2019-08-03 06:52发布

This is related to the following question: In scala, how to turn object's values into Map[String, String]?

In fact, I have almost exactly the same problem. However, the solution given in the accepted answer runs around 50x slower than productIterator (which returns only the values of the fields) when iterating 1000 times on my machine (or manually writing a function to return the list of (key, value) pairs). Is there a reasonably performant and clean way of getting the names of the fields of a case class in Scala? It seems strange to me that the core language would provide a performant reflection-like way of getting the values, but not the field names.

1条回答
贼婆χ
2楼-- · 2019-08-03 07:42

If you write and compile a case class, you can browse through the generated byte code and you will notice that the field names are not hardcoded anywhere into a method of the class. This means you must use reflection for finding out about these names. And reflective lookup is unfortunately expensive.

With the productIterator, there is however an approach for avoiding reflection. Any case class implements the Product trait which defines a method Object productElement(int) which will return the value of the field at a given index. Other than the field names, this information is hardcoded into a case class method. By internally using this method, the productIterator method avoids reflection and can be executed efficiently.

Bottom line: While reflective invocation is not so expensive, reflective lookup is. If you need the field name information, you should therefore only lookup the information once and cache the results for later reuse.

查看更多
登录 后发表回答