污染 $scope 对象会影响性能吗? [英] Does polluting the $scope object affect performance?
问题描述
我有一个控制器,其中 $scope 对象已用于存储仅在同一控制器内本地使用的方法和值.发生了很多这样的事情:
I have a controller where the $scope object has been used to store methods and values that are only used locally within the same controller. There is a lot of this going on:
$scope.foo = 'something';
$scope.bar = 'something else';
...等等.在视图中没有使用这些值.我的问题是污染 $scope 对象会影响性能吗?清理它以便只有视图所需的值和方法包含在 $scope 对象中是个好主意吗?
... and so on. None of these values are used within the view. My question is does polluting the $scope object affect performance? Is it a good idea to clean this up so only values and methods needed for the view are contained in the $scope object?
推荐答案
是的,污染 $scope
确实会影响性能,但这取决于您的范围有多个经常更改的观察者,这将创建一个更多的管理费用.请参阅这个答案,其中涵盖了相同的观点
Yes, Polluting $scope
does affect performance, but its depends your scope has multiple watchers which are frequently changing then that will create a more overhead cost. Refer this answer which has covered same point
为了避免这种情况,我建议您对代码进行良好的重构
For avoiding this situation I'd suggest you to do good re-factoring of code
在需要时处理控制器中的所有逻辑,否则通过充分利用每个组件来分离逻辑.
Handle all the logic in controller whenever required otherwise do separate a logic by making good use of each component.
- 将通用方法(逻辑)移到
service
/factory
/provider
中,多处使用,方便共享. - 如果某些值是固定的,它们不会改变,然后将它们移动到
constant
/value
- 每当您觉得自己有相同的逻辑需要保留在
$scope
中时,它就会将该逻辑移动到公共控制器中.需要时,您可以使用$controller
注入器 在当前控制器范围内注入
- Move common method(logic) to
service
/factory
/provider
which is used in multiple place, so that it would be sharable. - If some value are fixed, they are not gonna change then move them to
constant
/value
- Whenever you feel like you have same logic which needs to be keep in
$scope
it self then move that logic to common controller. When required you could inject in your current controller scope using$controller
injector
另请参阅对作用域的理解 清楚地了解范围的使用
Also refer Understanding Of Scope for clear understanding of use of scope
这篇关于污染 $scope 对象会影响性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!