Skip to content

Instantly share code, notes, and snippets.

@ignasi35
Created August 29, 2014 07:51
Show Gist options
  • Save ignasi35/03bbced04a181f155163 to your computer and use it in GitHub Desktop.
Save ignasi35/03bbced04a181f155163 to your computer and use it in GitHub Desktop.
A tailrecursive counter to generate some test bytecode for jitwatch
import scala.annotation.tailrec
object Hello {
def main(args: Array[String]):Unit = {
val i = inc(0, 10000)
println(i)
}
@tailrec
def inc(i:Int, iter:Int):Int=if(iter>0) inc(i+1, iter-1) else i
}
@chriswhocodes
Copy link

Hi Ignasi,
Here is the bytecode for the tailrec version of inc:
0: iload_2
1: iconst_0
2: if_icmple 16
5: iload_1
6: iconst_1
7: iadd
8: iload_2
9: iconst_1
10: isub
11: istore_2
12: istore_1
13: goto 0
16: iload_1
17: ireturn

@tailrec nicely eliminates the method calls with the goto

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment