从另一个表达式中深入访问标量表达式多次的最简洁和字节码有效方法是什么?
以下代码中的所有函数(exc。标量4 )都可以根据需要运行。但只有字节编码器会发出有效的字节码(尽管它与ISTORE 2 ILOAD 2结尾很糟糕),其他每个都产生了六个INVOKE&#39>。
这个习惯用法也可以方便地将元组的任意部分作为参数传递:
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)
}
public bytecoder()I
ALOAD 0
INVOKEVIRTUAL com/_601/hack/Hack$.intro ()I
ISTORE 1
ILOAD 1
ILOAD 1
SIPUSH 600
IDIV
IADD
ISTORE 2
ILOAD 2
IRETURN
答案 0 :(得分:2)
只需创建一个带临时值的本地块。认真。它很紧凑:比“惯用”管道长一个字符
{ 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
/ p>
答案 1 :(得分: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(){}
,牺牲了字节码和性能以支持样式。
此外,危险打破传统,每个参数只使用一次下划线。