2

从另一个表达式的深处多次访问标量表达式的最简洁和字节码有效的方法是什么?

以下代码(不包括 scalar4)中的所有函数都可以根据需要运行。但是只有字节编码器发出有效的字节码(尽管它以 ISTORE 2 ILOAD 2 结尾很糟糕),其他的每个生成六个 INVOKE。

这个习惯用法对于传递元组的任意部分作为参数也很方便:

for (a_tuple) { f(_._3, _._1) + g(_._2) }  // caution NOT legal Scala

在这个例子中, intro代表一个只应该被调用一次的昂贵函数。

object Hack extends App
{
  @inline final def fur[T, V](x :T)(f :T => V) :V = f(x)

  @inline final def pfor[T, V](x :T)(pf :PartialFunction[T, V]) = pf(x)

  @inline final def cfor[T, V](x :T)(f :T => V) :V = x match { case x => f(x) }

  def intro :Int = 600 // only one chance to make a first impression

  def bytecoder = intro match { case __ => __ + __ / 600 }

  def functional = fur(intro) (x => x + x / 600)

  def partial = pfor(intro) { case __ => __ + __ / 600 }

  def cased = cfor(intro) ($ => $ + $ / 600)

  def optional = Some(intro).map(? => ? + ? / 600).get

  def folder = Some(intro).fold(0)(? => ? + ? / 600)

  // the for I wish for
  def scalar4 = for(intro) (_ + _ / 600) // single underline!

  println(bytecoder, functional, partial, cased, optional, folder)
}

公共字节编码器()我

ALOAD 0
INVOKEVIRTUAL com/_601/hack/Hack$.intro ()I
ISTORE 1
ILOAD 1
ILOAD 1
SIPUSH 600
IDIV
IADD
ISTORE 2
ILOAD 2
IRETURN
4

2 回答 2

2

只需使用临时 val 创建一个本地块。严重地。它很紧凑:只比“惯用”管道长一个字符

{ val x = whatever; x * x / 600 }
whatever match { case x => x * x / 600 }
whatever |> { x => x * x / 600 }

它很有效:可能的最小字节码。

// def localval = { val x = whatever; x * x / 600 }
public int localval();
  Code:
   0:   aload_0
   1:   invokevirtual   #18; //Method whatever:()I
   4:   istore_1
   5:   iload_1
   6:   iload_1
   7:   imul
   8:   sipush  600
   11:  idiv
   12:  ireturn

它唯一不做的就是充当后缀运算符,match当你真的需要那种形式并且不能容忍额外的字节码时,你就可以做到这一点。

于 2013-02-28T23:20:11.780 回答
1
// Canadian scalar "for" expression
@inline final case class four[T](x: T)
{
  @inline def apply(): T = x

  @inline def apply[V](f: Function1[T,          V]): V = f(x)
  @inline def apply[V](f: Function2[T, T,       V]): V = { val $ = x; f($, $) }
  @inline def apply[V](f: Function3[T, T, T,    V]): V = { val $ = x; f($, $, $) }
  @inline def apply[V](f: Function4[T, T, T, T, V]): V = { val $ = x; f($, $, $, $) }
  // ...
}

// Usage
val x = System.currentTimeMillis.toInt % 1 + 600

def a = four(x)() + 1
def b = four(x)(_ + 1)
def c = four(x)(_ + _ / x)
def d = four(x)(_ + _ / _)
def e = four(x)(_ + _ / _ - _) + 600

println(a, b, c, d, e)

有了这个four(){},字节码和性能被牺牲了,有利于风格。

此外,这危险地打破了传统,即每个参数仅使用一次下划线。

于 2013-03-10T12:47:08.177 回答