0

I have a very simple test cases(scalatest, but doesn't matter) and I provide two implementation of accessing some resources, this method returns either Try or some case class instance.

Test cases:

"ResourceLoader" must
    "successfully initialize resource" in {
    /async code test
    noException should be thrownBy Await.result(ResourceLoader.initializeRemoteResourceAsync(credentials, networkConfig), Duration.Inf)
    }

"ResourceLoader" must
    "successfully sync initialize remote resources" in {
    noException should be thrownBy ResourceLoader.initializeRemoteResource(credentials, networkConfig)
  }

This tests testing different code which access some remote resources

Sync version

def initializeRemoteResource(credentials: Credentials, absolutePathToNetworkConfig: String): Resource = {
  //some code accessing remote server
}

Async version

def initializeRemoteResourceAsync(credentials: Credentials, absolutePathToNetworkConfig: String): Future[Try[Resource]] = {
  Future {
    //the same code as in sync version
  }
}

In IDEA test tab I see that future based version is twice slower then sync version, my question is there overhead for calling Await.result explicitly? If not, why it slows down the execution? Appreciate any help, Thanks.

Note: I know it is not the best way to measure performance of production system. But it at list says how much time was spend on each test case.

Slow Harry
  • 1,857
  • 3
  • 24
  • 42

1 Answers1

2

Yes, there will be a small overhead for Await.result, but in practice it probably doesn't amount to much. Future {} requires an ExecutionContext (thread pool or thread creator) in implicit scope so you won't be able to successfully use it without importing the default execution context (which will simply spawn a thread) or some other context. If you're using the default execution context, for example, you will have two threads instead of one which will involve some overhead for context switching. It shouldn't be much though. If 'twice as slow' means 40ms instead of 20 then perhaps it's not worth worrying about.

john_omalley
  • 1,398
  • 6
  • 13
  • What is consuming more time, Await.result call or getting future from thread pool ? I actually wonder, how to identify right use case for future operation. Or how time consuming operation should be, to run it asynchronously, to make things faster? – Slow Harry Oct 12 '16 at 07:54
  • Await.result simply blocks the current thread until the future completes in the background thread. How long it takes to get a thread from the thread pool depends on what kind of ExecutionContext you're using. Generally these things are super-fast, and I/O takes an order of magnitude more time. – john_omalley Oct 12 '16 at 23:50