diff options
author | Paul Phillips <paulp@improving.org> | 2009-08-28 17:44:47 +0000 |
---|---|---|
committer | Paul Phillips <paulp@improving.org> | 2009-08-28 17:44:47 +0000 |
commit | 0c910180fb8a300dbe84b612dc78d5a83b16c748 (patch) | |
tree | a3d890e904e0bed638b9a85e9d52a430689f5824 /src | |
parent | de60f2481fe773e4435e2a347983dfbf7f7d2d05 (diff) | |
download | scala-0c910180fb8a300dbe84b612dc78d5a83b16c748.tar.gz scala-0c910180fb8a300dbe84b612dc78d5a83b16c748.tar.bz2 scala-0c910180fb8a300dbe84b612dc78d5a83b16c748.zip |
Added a times method to RichInt.
against in the past but I collected performance numbers on every
available approach to repeating something and this is by far the winning
combination in speed and clarity. Elaboration available if anyone still
feels strongly negative about it.
Diffstat (limited to 'src')
-rw-r--r-- | src/library/scala/runtime/RichInt.scala | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/src/library/scala/runtime/RichInt.scala b/src/library/scala/runtime/RichInt.scala index 47d4b458c1..0c950cef8d 100644 --- a/src/library/scala/runtime/RichInt.scala +++ b/src/library/scala/runtime/RichInt.scala @@ -32,6 +32,23 @@ final class RichInt(val start: Int) extends Proxy with Ordered[Int] { def max(that: Int): Int = if (start > that) start else that def abs: Int = if (start < 0) -start else start + /** Execute a block of code this many times. + * For instance: 5 times { println("hello") } + * + * N.B. this way of repeatedly executing an action has + * far superior performance to any other approach in the + * library. It's not just syntactic sugar, it is faster + * than anything but a locally implemented while loop and + * of course less error prone than the while loop. + */ + def times(body: => Unit) { + var i = 0 + while (i < start) { + body + i += 1 + } + } + def toBinaryString: String = java.lang.Integer.toBinaryString(start) def toHexString: String = java.lang.Integer.toHexString(start) def toOctalString: String = java.lang.Integer.toOctalString(start) |