Skip to content

Commit

Permalink
util-core: Optimize Future.delayed
Browse files Browse the repository at this point in the history
Problem / Solution

`Future.delayed` could be optimized w.r.t allocations (7% fewer allocations).

RB_ID=916943
  • Loading branch information
vkostyukov authored and jenkins committed May 25, 2017
1 parent 94ab01f commit 21747f6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
Expand Up @@ -191,6 +191,9 @@ class FutureBenchmark extends StdBenchAnnotations {
}
Await.result(f)
}

@Benchmark
def timeDelayed(): Future[Unit] = Future.Done.delayed(Duration.Top)(Timer.Nil)
}

object FutureBenchmark {
Expand Down
14 changes: 7 additions & 7 deletions util-core/src/main/scala/com/twitter/util/Future.scala
Expand Up @@ -1094,14 +1094,14 @@ abstract class Future[+A] extends Awaitable[A] { self =>
* Delay the completion of this Future for at least
* `howlong` from now.
*/
def delayed(howlong: Duration)(implicit timer: Timer): Future[A] = {
if (howlong == Duration.Zero)
return this
def delayed(howlong: Duration)(implicit timer: Timer): Future[A] =
if (howlong == Duration.Zero) this
else new Promise[A] with (() => Unit) { other =>
def apply(): Unit = become(self)

val p = Promise.interrupts[A](this)
timer.schedule(howlong.fromNow) { p.become(this) }
p
}
timer.schedule(howlong.fromNow)(other())
forwardInterruptsTo(self)
}

/**
* When this future completes, run `f` on that completed result
Expand Down

0 comments on commit 21747f6

Please sign in to comment.