StatefullWidget 和 StatelessWidget 在性能方面有什么区别? [英] What is the difference between StatefullWidget and StatelessWidget regards to Performance?

查看:17
本文介绍了StatefullWidget 和 StatelessWidget 在性能方面有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们只使用 StatefullWidget 而不是 StatelessWidget 是否会影响性能,反之亦然?

Is there a Performance impact if we just use StatefullWidget over the StatelessWidget it vice-versa?

在我看来,我们只是将 StatefullWidget 用于使用 setState() 更新 UI 的一部分,有一种方法可以在 StatefullWidget 中设置一些代码code>initState() 并在 dispose() 函数中处理东西.因此,当我不需要这些东西时,我会继续使用 StatelessWidget.

In my point of view, we just use StatefullWidget for things like update part of the UI using setState(), have a way to setup some code in the initState() and dispose things in the dispose() function. So when I don't need those things I go ahead and use StatelessWidget.

但这两个最常用的小部件之间真正的性能影响是什么?

But what is the real performance impact between these two most used widgets?

推荐答案

性能方面,StatelessWidget 几乎等同于具有空 State 的 StatefulWidget.

Performance-wise, a StatelessWidget is almost identical to a StatefulWidget with an empty State.

写作:

class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

或:

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

不会对您的应用性能产生任何明显的影响.

won't have any visible impact on the performance of your app.

在此处使用 StatelessWidget 确实有一点好处.但它太小了:

There indeed is a small gain when using StatelessWidget here. But it's ridiculously small:

它们之间的区别可以概括为调用空函数与不调用它.有关系,但绝对不重要.

The difference between them can be summarized as calling an empty function vs not calling it. It's something, but absolutely doesn't matter.

原因是,StatefulWidgetStatelessWidget的内部实现几乎是一样的.

The reason being, internally the implementation of StatefulWidget and StatelessWidget is almost the same.

StatelessWidget 确实 拥有 StatefulWidget 拥有的所有额外生命周期.它有一个initState"/dispose".甚至是一个 setState!它们只是不是公共 API 的一部分.

StatelessWidget does have all the extra life-cycles that StatefulWidget possess. It has an "initState"/"dispose". Even a setState! They are just not part of the public API.

这篇关于StatefullWidget 和 StatelessWidget 在性能方面有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆