Skip to content

Instantly share code, notes, and snippets.

@chick
Created August 6, 2014 18:55
Show Gist options
  • Save chick/7efce8e44b2a34cb1e74 to your computer and use it in GitHub Desktop.
Save chick/7efce8e44b2a34cb1e74 to your computer and use it in GitHub Desktop.
object reduce_vs_fold {
println("Welcome to Eclipse Scala worksheet") //> Welcome to Eclipse Scala worksheet
def time[A](f: => A) = {
val now = System.nanoTime
val result = f
val micros = (System.nanoTime - now) / 1000.0
println("%12.4f micro seconds".format(micros))
result
} //> time: [A](f: => A)A
val a = time(Array.tabulate(100000)( x => util.Random.nextDouble))
//> 38750.0000 micro seconds
//| a : Array[Double] = Array(0.6494449871627447, 0.3944213163608279, 0.3879756
//| 9727200987, 0.6299233458256341, 0.7337731563822277, 0.08374384043472749, 0.6
//| 187414133079476, 0.5920459843284207, 0.4207775384477208, 0.03771376791322289
//| 5, 0.13981062935305055, 0.3832567496603332, 0.39970286375198816, 0.344391495
//| 46946535, 0.32196739034561495, 0.6742217789803084, 0.6142433678961545, 0.494
//| 633963420701, 0.9556546875208423, 0.04043673927922464, 0.3146329810780646, 0
//| .14028952730663602, 0.27770713389856116, 0.14208941819772425, 0.828467725864
//| 924, 0.27285347541601246, 0.5258515850683053, 0.40600202438848443, 0.3746309
//| 8086650504, 0.27219975075843883, 0.24622631131168327, 0.501554144018367, 0.8
//| 35513875227377, 0.8111371432536196, 0.37311405905331607, 0.766744750468781,
//| 0.6497923248904091, 0.04392105603605212, 0.050279817106685165, 0.01105965538
//| 8251044, 0.8913432487720093, 0.8554846952325842, 0.2697497450347266, 0.798
//| Output exceeds cutoff limit.
val b = time(math.sqrt(a.map { x => math.pow(x, 2) }.reduce(_+_)))
//> 29987.0000 micro seconds
//| b : Double = 182.6325768548345
val c = time(math.sqrt(a.foldLeft(0.0) { (x, y) => x + math.pow(y, 2) }))
//> 7696.0000 micro seconds
//| c : Double = 182.6325768548345
println(a) //> [D@21270107
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment