darkjh
darkjh

Reputation: 2861

Unnecessary load and store instruction in scala's byte code

I just did some inverstigation on pattern match and its corresponding byte code.

val a = Array(1,2,3,4)
a.map {
  case i => i + 1
}

For above code, I use javap and got the byte code for the annonymous function inside map:

public int apply$mcII$sp(int);
Code:
   0: iload_1       
   1: istore_2      
   2: iload_2       
   3: iconst_1      
   4: iadd          
   5: ireturn       

So it seems to me that in line 0 we push an int (the parameter), then in line 1 we load the int and in line 2 we push it back ... What's the purpose here?

Thanks!

Upvotes: 5

Views: 195

Answers (2)

som-snytt
som-snytt

Reputation: 39577

Dude, try -optimise.

  public int apply$mcII$sp(int);
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=2, args_size=2
         0: iload_1       
         1: iconst_1      
         2: iadd          
         3: ireturn 

Use

scala> :javap -prv -

and then something like

scala> :javap -prv $line4/$read$$iw$$iw$$anonfun$1

Upvotes: 2

fresskoma
fresskoma

Reputation: 25791

This is not really an answer, since I couldn't figure out why this happens. I'm hoping that these observations will be at least helpful :)


I'm seeing the following bytecode in Scala 2.10:

public int apply$mcII$sp(int);
    Code:
       0: iload_1       ; var1 -> stack
       1: istore_2      ; var2 <- stack
       2: iload_2       ; var2 -> stack
       3: iconst_1      ; 1 -> stack
       4: iadd      
       5: istore_3      ; var3 <- stack
       6: iload_3       ; var3 -> stack
       7: ireturn       ; return <- stack

The first two instructions seem to simply move the value of var1 to var2, then move var2 to the stack as a parameter. The same can be observed after iadd, where the result is stored in var3 for no apparent reason, since ireturn returns the value from the stack anyway.

Upvotes: 1

Related Questions