首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >框架下的Groovy、Scala和Java

框架下的Groovy、Scala和Java
EN

Stack Overflow用户
提问于 2010-03-27 15:02:18
回答 6查看 3.4K关注 0票数 4

我使用长达6-7年,但几个月前我发现了Groovy,并开始节省大量输入.然后,我想知道某些东西是如何在幕后工作的(因为groovy性能真的很差),我明白要动态输入每个Groovy对象是一个MetaClass对象,它处理JVM自己无法处理的所有事情。当然,这在您所写的内容和执行的内容之间引入了一个中间层,从而减缓了一切。

几天前,我开始了解一些关于Scala的信息。这两种语言的字节码翻译比较如何?它们为普通Java代码获得的正常结构添加了多少东西?

我的意思是,Scala是静态类型的,所以Java类的包装应该更轻点,因为在编译期间检查了很多东西,但我不确定内部情况的真正区别。(我说的不是Scala与其他Scala相比的功能方面,这是另一回事)

有人能启发我吗?

SyntaxT3rr0r评论来看,获得较少输入和相同性能的唯一方法似乎是编写一个中间翻译程序,在不改变执行方式的情况下翻译Java代码(允许javac编译),只是添加语法糖,而不关心语言本身的其他后遗症。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-03-27 17:51:49

Scala在降低抽象成本方面做得越来越好。

在代码的内联注释中,我解释了Array access、pimped类型、结构类型以及对原语和对象的抽象的性能特征。

列阵

代码语言:javascript
运行
复制
object test {
  /**
   * From the perspective of the Scala Language, there isn't a distinction between
   * objects, primitives, and arrays. They are all unified under a single type system,
   * with Any as the top type.
   *
   * Array access, from a language perspective, looks like a.apply(0), or a.update(0, 1)
   * But this is compiled to efficient bytecode without method calls. 
   */
  def accessPrimitiveArray {
    val a = Array.fill[Int](2, 2)(1)
    a(0)(1) = a(1)(0)        
  }
  // 0: getstatic #62; //Field scala/Array$.MODULE$:Lscala/Array$;
  // 3: iconst_2
  // 4: iconst_2
  // 5: new #64; //class test$$anonfun$1
  // 8: dup
  // 9: invokespecial #65; //Method test$$anonfun$1."<init>":()V
  // 12:  getstatic #70; //Field scala/reflect/Manifest$.MODULE$:Lscala/reflect/Manifest$;
  // 15:  invokevirtual #74; //Method scala/reflect/Manifest$.Int:()Lscala/reflect/AnyValManifest;
  // 18:  invokevirtual #78; //Method scala/Array$.fill:(IILscala/Function0;Lscala/reflect/ClassManifest;)[Ljava/lang/Object;
  // 21:  checkcast #80; //class "[[I"
  // 24:  astore_1
  // 25:  aload_1
  // 26:  iconst_0
  // 27:  aaload
  // 28:  iconst_1
  // 29:  aload_1
  // 30:  iconst_1
  // 31:  aaload
  // 32:  iconst_0
  // 33:  iaload
  // 34:  iastore
  // 35:  return

拉皮条我的图书馆

代码语言:javascript
运行
复制
  /**
   * Rather than dynamically adding methods to a meta-class, Scala
   * allows values to be implicity converted. The conversion is
   * fixed at compilation time. At runtime, there is an overhead to
   * instantiate RichAny before foo is called. HotSpot may be able to
   * eliminate this overhead, and future versions of Scala may do so
   * in the compiler.
   */
  def callPimpedMethod {    
    class RichAny(a: Any) {
      def foo = 0
    }
    implicit def ToRichAny(a: Any) = new RichAny(a)
    new {}.foo
  }
  // 0: aload_0
  //   1: new #85; //class test$$anon$1
  //   4: dup
  //   5: invokespecial #86; //Method test$$anon$1."<init>":()V
  //   8: invokespecial #90; //Method ToRichAny$1:(Ljava/lang/Object;)Ltest$RichAny$1;
  //   11:  invokevirtual #96; //Method test$RichAny$1.foo:()I
  //   14:  pop
  //   15:  return

结构类型(又名鸭子类型)

代码语言:javascript
运行
复制
  /**
   * Scala allows 'Structural Types', which let you have a compiler-checked version
   * of 'Duck Typing'. In Scala 2.7, the invocation of .size was done with reflection.
   * In 2.8, the Method object is looked up on first invocation, and cached for later
   * invocations..
   */
  def duckType {
    val al = new java.util.ArrayList[AnyRef]
    (al: { def size(): Int }).size()
  }
  // [snip]
  // 13:  invokevirtual #106; //Method java/lang/Object.getClass:()Ljava/lang/Class;
  // 16:  invokestatic  #108; //Method reflMethod$Method1:(Ljava/lang/Class;)Ljava/lang/reflect/Method;
  // 19:  aload_2
  // 20:  iconst_0
  // 21:  anewarray #102; //class java/lang/Object
  // 24:  invokevirtual #114; //Method java/lang/reflect/Method.invoke:(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
  // 27:  astore_3
  // 28:  aload_3
  // 29:  checkcast #116; //class java/lang/Integer

专门性

代码语言:javascript
运行
复制
  /**
   * Scala 2.8 introduces annotation driven specialization of methods and classes. This avoids
   * boxing of primitives, at the cost of increased code size. It is planned to specialize some classes
   * in the standard library, notable Function1.
   *
   * The type parameter T in echoSpecialized is annotated to instruct the compiler to generated a specialized version
   * for T = Int.
   */
  def callEcho {    
    echo(1)
    echoSpecialized(1)
  }
  // public void callEcho();
  //   Code:
  //    Stack=2, Locals=1, Args_size=1
  //    0:   aload_0
  //    1:   iconst_1
  //    2:   invokestatic    #134; //Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
  //    5:   invokevirtual   #138; //Method echo:(Ljava/lang/Object;)Ljava/lang/Object;
  //    8:   pop
  //    9:   aload_0
  //    10:  iconst_1
  //    11:  invokevirtual   #142; //Method echoSpecialized$mIc$sp:(I)I
  //    14:  pop
  //    15:  return


  def echo[T](t: T): T = t
  def echoSpecialized[@specialized("Int") T](t: T): T = t
}

闭包和理解

在Scala中,for被转换为一个高阶函数的调用链:foreachmapflatMapwithFilter。这是非常强大的,但是您需要意识到,下面的代码并不像Java中类似的构造那样高效。Scala2.8将至少为Function1和Int专门化Traversable#foreach,并希望@SpecificationTraversable#foreach,这至少将消除装箱成本。

以闭包的形式传递用于理解的主体,该闭包被编译到匿名的内部类中。

代码语言:javascript
运行
复制
def simpleForLoop {
  var x = 0
  for (i <- 0 until 10) x + i
}
// public final int apply(int);   
// 0:   aload_0
// 1:   getfield    #18; //Field x$1:Lscala/runtime/IntRef;
// 4:   getfield    #24; //Field scala/runtime/IntRef.elem:I
// 7:   iload_1
// 8:   iadd
// 9:   ireturn


// public final java.lang.Object apply(java.lang.Object);

// 0:   aload_0
// 1:   aload_1
// 2:   invokestatic    #35; //Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
// 5:   invokevirtual   #37; //Method apply:(I)I
// 8:   invokestatic    #41; //Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
// 11:  areturn

// public test$$anonfun$simpleForLoop$1(scala.runtime.IntRef);
// 0:   aload_0
// 1:   aload_1
// 2:   putfield    #18; //Field x$1:Lscala/runtime/IntRef;
// 5:   aload_0
// 6:   invokespecial   #49; //Method scala/runtime/AbstractFunction1."<init>":()V
// 9:   return

LineNumberTable:第4行:0

代码语言:javascript
运行
复制
// 0:   new #16; //class scala/runtime/IntRef
// 3:   dup
// 4:   iconst_0
// 5:   invokespecial   #20; //Method scala/runtime/IntRef."<init>":(I)V
// 8:   astore_1
// 9:   getstatic   #25; //Field scala/Predef$.MODULE$:Lscala/Predef$;
// 12:  iconst_0
// 13:  invokevirtual   #29; //Method scala/Predef$.intWrapper:(I)Lscala/runtime/RichInt;
// 16:  ldc #30; //int 10
// 18:  invokevirtual   #36; //Method scala/runtime/RichInt.until:(I)Lscala/collection/immutable/Range$ByOne;
// 21:  new #38; //class test$$anonfun$simpleForLoop$1
// 24:  dup
// 25:  aload_1
// 26:  invokespecial   #41; //Method test$$anonfun$simpleForLoop$1."<init>":(Lscala/runtime/IntRef;)V
// 29:  invokeinterface #47,  2; //InterfaceMethod scala/collection/immutable/Range$ByOne.foreach:(Lscala/Function1;)V
// 34:  return
票数 23
EN

Stack Overflow用户

发布于 2010-03-28 00:32:46

很多好的答案,我会尝试补充一些从你的问题中得到的东西。Scala对象没有包装。例如,以下两个类分别在Scala和Java中生成完全相同的字节码:

代码语言:javascript
运行
复制
// This is Scala
class Counter {
  private var x = 0
  def getCount() = {
    val y = x
    x += 1
    y
  }
}

// This is Java
class Counter {
  private int x = 0;

  private int x() {
    return x;
  }

  private void x_$eq(int x) {
    this.x = x;
  }

  public int getCounter() {
    int y = x();
    x_$eq(x() + 1);
    return y;
  }
}

特别要注意的是,Scala总是通过getters和setter访问字段,甚至在同一个类的其他方法上也是如此。然而,关键是这里绝对没有类包装。无论是用Java还是Scala编译,情况都是一样的。

现在,Scala使编写更慢的代码变得更容易。它的一些例子是:

  • Scala的for在增量索引时比Java慢得多--到目前为止,解决方案是使用while循环,尽管有人编写了一个自动转换的编译器插件。迟早会添加这样的优化。
  • 在Scala中编写闭包和传递函数非常容易。它使代码更具可读性,但它比没有在紧循环中执行代码要慢得多。
  • 参数化函数也很容易,这样就可以通过Int,如果您正在处理原语(在Scala中,AnyVal子类中),这会导致性能不好。

下面是一个用Scala以两种不同方式编写的类的示例,其中更紧凑的类的速度大约是Scala的两倍:

代码语言:javascript
运行
复制
class Hamming extends Iterator[BigInt] {
  import scala.collection.mutable.Queue
  val qs = Seq.fill(3)(new Queue[BigInt])
  def enqueue(n: BigInt) = qs zip Seq(2, 3, 5) foreach { case (q, m) => q enqueue n * m }
  def next = {
    val n = qs map (_.head) min;
    qs foreach { q => if (q.head == n) q.dequeue }
    enqueue(n)
    n
  }
  def hasNext = true
  qs foreach (_ enqueue 1)
}

class Hamming extends Iterator[BigInt] {
  import scala.collection.mutable.Queue
  val q2 = new Queue[BigInt]
  val q3 = new Queue[BigInt]
  val q5 = new Queue[BigInt]
  def enqueue(n: BigInt) = {
    q2 enqueue n * 2
    q3 enqueue n * 3
    q5 enqueue n * 5
  }
  def next = {
    val n = q2.head min q3.head min q5.head
    if (q2.head == n) q2.dequeue
    if (q3.head == n) q3.dequeue
    if (q5.head == n) q5.dequeue
    enqueue(n)
    n
  }
  def hasNext = true
  List(q2, q3, q5) foreach (_ enqueue 1)
}

这也是一个很好的例子,说明如何在需要时平衡性能是完全可能的。例如,更快的版本在构造函数中使用foreach,它不会导致性能问题。

最后,这都是一个透视的问题。在对象上调用方法比直接调用函数和过程要慢,这是面向对象编程的主要反对因素,但在大多数情况下,这并不是什么大问题。

票数 10
EN

Stack Overflow用户

发布于 2010-03-27 15:09:37

需要注意的一点是: Java 7将为JVM引入一个新的发票动态字节码,这将使许多Groovy的“元类魔术”变得不必要,并且应该大大加快JVM上的动态语言实现。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2529736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档