在 Scala 中获取案例类字段名称的最快方法 [英] Fastest way to get the names of the fields of a case class in Scala

查看:33
本文介绍了在 Scala 中获取案例类字段名称的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与以下问题有关:在scala,如何将对象的值转化为Map[String, String]?

事实上,我遇到了几乎完全相同的问题.但是,在我的机器上迭代 1000 次(或手动编写函数以返回列表)时,接受的答案中给出的解决方案比 productIterator(仅返回字段的值)慢 50 倍(键,值)对).是否有一种性能合理且干净的方法来获取 Scala 中案例类的字段名称?对我来说,核心语言会提供一种类似于反射的高性能方式来获取值,而不是字段名称,这对我来说似乎很奇怪.

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.

推荐答案

如果你编写并编译一个 case 类,你可以浏览生成的字节码,你会注意到字段名称没有硬编码到方法的任何地方班上.这意味着您必须使用反射来查找这些名称.不幸的是,反射查找很昂贵.

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.

对于productIterator,有一种避免反射的方法.任何 case 类都实现了 Product trait,它定义了一个方法 Object productElement(int),它将返回给定索引处的字段值.除了字段名称之外,此信息被硬编码到案例类方法中.通过内部使用此方法,productIterator 方法避免了反射并且可以高效执行.

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.

这篇关于在 Scala 中获取案例类字段名称的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆