gpt4 book ai didi

javascript - RxJS 中的 If 与 Filter 性能比较

转载 作者:行者123 更新时间:2023-12-03 00:14:05 25 4
gpt4 key购买 nike

考虑一个 RxJS 的示例。

A 型:[使用过滤器]

this.userService.afAuth.authState
.pipe(filter(user => !!user))
.subscribe( _ => this.router.navigate(["/anything"]) )

B 型:[使用 if]

this.userService.afAuth.authState
.subscribe( user => {
if(!!user) this.router.navigate(["/anything"])
})

Q1. How do we compare the performance?

Q2. Which is recommended and why?

最佳答案

Q1. How do we compare the performance?

您可以使用https://jsperf.com/创建您的性能测试。我可以告诉你,“B 型”的性能一定更好,因为涉及的函数调用更少。仅当您真正经常调用该函数时(粗略估计可能为每秒 10,000 次调用),这一点才会引人注目。对于典型的用例,不会有什么区别。

Q2. Which is recommended and why?

从设计的 Angular 来看,推荐“A型”。它具有更具声明性的语法,因此更容易替换或重用。例如,您的 filter 管道可以提取到可重复使用的管道中并多次使用。如果您的谓词在某个时刻发生变化,您只需更改一次。

关于javascript - RxJS 中的 If 与 Filter 性能比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54596672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com