The creation of ActorMaterializer
s is fairly cheap and having a reasonable proliferation of them shouldn't be an issue in the majority of cases.
If you chase the chain of calls starting from ActorMaterializer.apply
(see source code) you'll find that ActorMaterializer
(or better, ActorMaterializerImpl
) is not performing anything significant at creation time.
Just to give you an idea of how it compares to an ActorSystem
creation, consider the following code
val sysStart = System.nanoTime()
val actorSystem = ActorSystem("mySystem")
val sysDuration = FiniteDuration(System.nanoTime() - sysStart, TimeUnit.NANOSECONDS)
println(s"System creation: ${sysDuration.toMillis} ms")
val matStart = System.nanoTime()
val materializer = ActorMaterializer()(actorSystem)
val matDuration = FiniteDuration(System.nanoTime() - matStart, TimeUnit.NANOSECONDS)
println(s"Materializer creation: ${matDuration.toMillis} ms")
outputs this on my laptop
System creation: 901 ms
Materializer creation: 14 ms
However, as Johan pointed out in the comments, it is important to add that materializers' lifecycle needs to be properly managed, invoking shutdown
whenever they stop being useful, to avoid leaking resources.
To recap, passing a materializer around whenever possible is a sound choice. Whenever this is not convenient though, its creation is cheap, but pay attention to shut it down properly.