英文:
Is there performance impact of using `map() + stream()` vs `flatMapMany() + map()`?
问题
使用 map() + stream()
和 flatMapMany() + map()
之间的性能差异是否有差异?
例如,我们有一组实体并且需要将其映射到这些对象的另一种表示:
List<Entity> list = ... // 初始化一些集合
Mono.just(collection)
.map(collection -> collection.stream.map(mapper::map))
.flatMapMany(Flux::fromStream)
或者
List<Entity> list = ... // 初始化一些集合
Mono.just(collection)
.flatMapMany(Flux::fromIterable)
.map(mapper::map)
在我看来,Stream.map 操作比 Flux.map 更轻量,并分配更少的对象,因此第一种解决方案更好,但我不太确定。
英文:
Is there difference in performance between using map() + stream()
and flatMapMany() + map()
?
For example, we have a collection of some entities and we need to map it to another representation of these objects:
List<Entity> list = ... // init some collection
Mono.just(collection)
.map(collection -> collection.stream.map(mapper::map))
.flatMapMany(Flux::fromStream)
OR
List<Entity> list = ... // init some collection
Mono.just(collection)
.flatMapMany(Flux::fromIterable)
.map(mapper::map)
In my opinion, Stream.map operations are more lightweight than Flux.map and allocate fewer objects, so then the first solution is better, but I'm not quite sure.
答案1
得分: 1
I don't think you should choose from those two.
It depends on which task is executed by your mapper.
If there will be some blocking or long-executed operation which you have wrapped with Mono - the best one will be:
List
Flux.fromIterable(list)
.map(mapper::map)
...
Whether you worry about objects count, you can use Stream.map on the list itself:
List
List
it is on your consideration which one to choose, I can only assume that you still have to return some Mono/Flux from your method, so you will not achieve many benefits from those redundant steps.
Speaking about two examples you've provided, it looks like incorrect usage, since it makes redundant conversion from Mono to Flux.
英文:
I don't think you should choose from those two.
It depends on which task is executed by your mapper.
If there will be some blocking or long executed operation which you have wrapped with Mono - the best one will be:
List<Entity> list = ... // init some collection
Flux.fromIterable(list)
.map(mapper::map)
...
Whether you worry about objects count, you can use Stream.map on list itself:
List<Entity> list = ... // init some collection
List<Entity> processedEntities = list.stream().map(mapper::map).toList();
it is on your consideration which one to choose, I can only assume that you still have to return some Mono/Flux from your method, so you will not achieve many benefits from those redundant steps.
Speaking about two examples you've provided, its looks like incorrect usage, since it makes redundant convertation from Mono to Flux
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论