Home » 未分类 » 资源加载请绕行bulkloader这个大坑

资源加载请绕行bulkloader这个大坑

由于历史原因,项目中使用了bulkloader作为底层的加载。bulkLoader简单易用,功能强大,这是他的优点。但从他的历史轨迹以及Github上的更新记录来看,已经5年没有更新了。

如果仅仅是因为他5年未有更新,就断定它“年老体衰”,是个大坑,那坑定不合逻辑。

它的坑,主要表现在性能方面。如果你仔细看过代码,会发现,在BuilLoader.as这个主入口类中,大量不合理的设计。比如,事件满天飞,比如每完成一个,就会遍历所有loadingItems,每次遍历都会把数组复制一遍。这么肆无忌惮的滥用Array,滥用循环,会对Flash Player内存回收造成比较严重的负担。尤其是对于大型网页游戏,资源加载数量惊人,简直就是卡得不要不要的。这里的卡不仅仅是本人主观上的感受,而是通过Scout CC监控,建立在数据基础之上的结论。

对于没有采用BulkLoader的项目,建议另辟蹊径。对于已经采用bulkloader的项目,并且依赖比较难处理,我们采取了解决方案就是重构bulkloader.

主要的优化就是:

1、把所有添加进行的loadingItems进行分组管理,这样可以有效的降低对象在状态发生改变的时候,遍历的长度。然后自行编写一些关于数组排序的算法,有效避免大量临时变量在内存中的分配。

2、删掉一些非常鸡肋的代码,尽量简化代码。

3、延迟排序优先级,不要再add()过程立即排序,而是标记一个状态“needResort”,在loadNext()之前,判断状态,如果需要排序,才进行一次排序。

4、缓存整体加载状态。比如在原来的Builloader中,判断是否全部加载完成的接口isAllComplete(),是建立在遍历每一个元素的基础之上。想想都觉得要吐。

5、事件Hander,采用var halder:Function 缓存,减少MethodClosure对象的重复创建

在这里推荐一个基于“信号”的加载库:https://github.com/Matan/AssetLoader .

下面是它的一些特性,准备自己写loader库的同学,可以借鉴一下。取其精华,去其糟粕,博采众长。

  • Automatic Type detection.
  • Multiple connections, which you can define = faster loading = less waiting = happier users.
  • No Events, AS3Signals only.
  • No singletons! Construct as many AssetLoaders as you want!
  • Data is dispatched with strong types. NO CASTING!
  • Endless recursive group loaders within loaders, within loaders, etc.
  • Pause/Resume/Destroy capabilities.
  • Dynamic parameter system that works with code completion – No guessing!
  • Loader parameters smartly inherit from their parent loaders, which mean you write less code.
  • Real-time loading stats. This provides latency, speed, average and progress of all downloads.
  • Consolidated stats, loaders reclusively consolidate loading stats all the way down to the last child.
  • Can be configured via XML, straight up or from an external file with one easy call.
  • All loader errors are consolidated to one signal. IOError, SecurityError, etc. – you don’t have to worry about it, they all boil down to one place. Which means you can “globally” handle loading errors with one listener/command.
  • Interfaces all round.
  • Unit tested! :D
  • Works super well with  Robotlegs//what doesn’t :P
  • And some other stuff too!
    分享到: