fork download
  1. class Test(var x: Float, var y: Float) {
  2. @inline final def :=(x: Float, y: Float) = {
  3. this.x = x
  4. this.y = y
  5. }
  6. @inline final def :=(o: Test) = { //reassign from arg "o"
  7. x = o.x
  8. y = o.y
  9. }
  10. @inline final def :=(of: (Test) => Unit) = { //apply mutating function "of"
  11. of(this)
  12. }
  13. @inline final def something_m = { //just an example of mutating function that does something
  14. x = 42
  15. }
  16. override def toString() = x.toString() + ", " + y.toString()
  17. }
  18.  
  19. object Benchmark {
  20. @inline final def benchmark(name: String, fun: () => Any) = {
  21. val t1 = System.currentTimeMillis()
  22. val res = fun()
  23. val t2 = System.currentTimeMillis()
  24. name + ": " + (t2 - t1).toFloat / 1000 + "sec; Result:" + res.toString()
  25. }
  26. val tmp = new Test(0, 0)
  27. @inline final def calc_something_for_reassign(a: Float, b: Float) = { //Assigns result to temporary object and exposes it (it's also dangerous)
  28. tmp := (a, b)
  29. tmp.something_m
  30. tmp
  31. }
  32. @inline final def calc_something_for_forwarding(a: Float, b: Float) = { //Creates a function that modifies its argument to the result
  33. (result: Test) =>
  34. {
  35. result := (a, b)
  36. result.something_m
  37. }
  38. }
  39.  
  40. @inline final def run_a(spins: Int) = {
  41. val x = 2f
  42. val y = 3f
  43. benchmark("reassignment", () => {
  44. val v = new Test(x, y)
  45. var i = spins
  46. while (i > 0) {
  47. i -= 1
  48. v := calc_something_for_reassign(v.x, v.y) //Calculates temporary value and assigns it to `v`
  49. }
  50. v
  51. })
  52. }
  53.  
  54. @inline final def run_b(spins: Int) = {
  55. val x = 2f
  56. val y = 3f
  57. benchmark("forwarding", () => {
  58. val v = new Test(x, y)
  59. var i = spins
  60. while (i > 0) {
  61. i -= 1
  62. v := calc_something_for_forwarding(v.x, v.y) //Forwards `v` to mutating function created in right-hand side
  63. }
  64. v
  65. })
  66. }
  67. }
  68.  
  69. object Main {
  70. def main(args: Array[String]) {
  71. println(Benchmark.run_a(Int.MaxValue/100))
  72. println(Benchmark.run_b(Int.MaxValue/100))
  73. println(Benchmark.run_b(Int.MaxValue/100))
  74. println(Benchmark.run_a(Int.MaxValue/100))
  75. }
  76. }
Success #stdin #stdout 0.95s 247424KB
stdin
Standard input is empty
stdout
reassignment: 0.091sec; Result:42.0, 3.0
forwarding: 0.272sec; Result:42.0, 3.0
forwarding: 0.241sec; Result:42.0, 3.0
reassignment: 0.092sec; Result:42.0, 3.0