Are there any difference calling run.db
once:
val dbAction3 = for {
res1 <- dbAction1
res2 <- dbAction2(res1)
} yield res2
val res3 = db.run(dbAction3)
and multiple times:
val res3 = for {
res1 <- db.run(dbAction1)
res2 <- db.run(dbAction2(res1))
} yield res2
As far as I understand, there is no difference unless we use transactionally
in the first one.
CodePudding user response:
The observable effect of the two is the same, but they execute in different ways. The first version creates a single query that is passed to the database whereas the second creates two separate database queries.
The first version gives greater potential for optimisation if there is any commonality between the two actions. (e.g. if both actions use the same tables/views). A good database might be able to combine or re-order operations for greater efficiency in a way that would not be possible with separate queries.
The second version incurs the overhead of two database operations and uses the Future
mechanism to serialise them rather than internal database mechanisms, so is likely to be less efficient.
There are no downsides to the first version and it might execute more efficiently, so that is the "better" choice. But it does depend on the particular database implementation so there may be cases where the second version is faster.