污染$ scope对象是否会影响性能? [英] Does polluting the $scope object affect performance?

查看:110
本文介绍了污染$ scope对象是否会影响性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,其中$ 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.

  1. 将通用方法(逻辑)移动到在多个地方使用的service/factory/provider,以便可以共享.
  2. 如果某个值是固定的,则它们不会改变,然后将其移至constant/value
  3. 每当您觉得需要保留在$scope中的逻辑相同时,它就会自行将该逻辑移至通用控制器.必要时,您可以使用$controller注入器
  4. 注入当前的控制器范围
  1. Move common method(logic) to service/factory/provider which is used in multiple place, so that it would be sharable.
  2. If some value are fixed, they are not gonna change then move them to constant/value
  3. 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屋!

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