Created
September 30, 2014 10:49
-
-
Save MysterionRise/5daa63fdbd5d058528fe to your computer and use it in GitHub Desktop.
Scala for, foreach, while, tailrec comparison
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util._ | |
import java.io._ | |
import java.util | |
import scala.annotation.tailrec | |
object Test { | |
var out: PrintWriter = null | |
var br: BufferedReader = null | |
var st: StringTokenizer = null | |
val upperBound = Integer.MAX_VALUE / 100 | |
def next: String = { | |
while (st == null || !st.hasMoreTokens) { | |
st = new StringTokenizer(br.readLine) | |
} | |
return st.nextToken | |
} | |
def nextInt: Int = { | |
return Integer.parseInt(next) | |
} | |
def nextLong: Long = { | |
return java.lang.Long.parseLong(next) | |
} | |
@tailrec | |
def recursion(i: Int): Unit = { | |
if (i < Test.upperBound) { | |
val z: Double = Math.pow(i, 2000) | |
if (z % 234541 == 0) { | |
println(z) | |
} | |
recursion(i + 1) | |
} | |
} | |
def solve: Int = { | |
val start1 = System.currentTimeMillis() | |
(0 until upperBound).foreach({ | |
x => | |
val z: Double = Math.pow(x, 2000) | |
if (z % 234541 == 0) { | |
println(z) | |
} | |
}) | |
out.println(".foreach " + (System.currentTimeMillis() - start1)) | |
val start2 = System.currentTimeMillis() | |
for (i <- 0 until upperBound) { | |
val z: Double = Math.pow(i, 2000) | |
if (z % 234541 == 0) { | |
println(z) | |
} | |
} | |
out.println("for " + (System.currentTimeMillis() - start2)) | |
val start3 = System.currentTimeMillis() | |
var i = 0 | |
while (i < upperBound) { | |
val z: Double = Math.pow(i, 2000) | |
if (z % 234541 == 0) { | |
println(z) | |
} | |
i += 1 | |
} | |
out.println("while " + (System.currentTimeMillis() - start3)) | |
val start4 = System.currentTimeMillis() | |
i = 0 | |
recursion(i) | |
out.println("tailrec " + (System.currentTimeMillis() - start4)) | |
return 1 | |
} | |
def main(args: Array[String]): Unit = { | |
br = new BufferedReader(new InputStreamReader(System.in)) | |
out = new PrintWriter(new BufferedOutputStream(System.out)) | |
solve | |
out.close | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment