关于性能优化,什么时候上线协程?

var time = new Date().getTime();
        
        for (var i = 0; i < list.length; i++) {
            var r = list[i]
            var node = this.list.children[i];
            if (!node) {
                node = this.getItem();
                this.list.addChild(node);
            }
            cc.find('rank', node).getComponent(cc.Label).string = i + 1;
            cc.find('name', node).getComponent(cc.Label).string = r.nickname;
            cc.find('winOrLose', node).getComponent(cc.Label).string = r.bigwin;
        }

        console.log("update,time:" + (new Date().getTime() - time));

这样一段代码,list.length大概等于100,居然需要大概1秒时间,很明显的卡一下,怎么优化?

http://cocos.com/docs/creator/api/modules/cc.html#method_find

每一个cc.find都是一个遍历

给ITEM 挂一个专用脚本来处理初始化吧

每帧只处理一个问题就解决了:slightly_smiling:

还是要有协程处理起来会方便一点。

@dowling 前輩,請問協程是指javascript可以寫出協程嗎?

JS是单线程的,我觉得所谓的协程、异步在JS里本质上就是JS引擎事件和setTimeout(setInterval)吧。看一下这样是不是不那么卡:

var time = new Date().getTime(), finished = 0;
for (var i = 0; i < list.length; i++) {
    setTimeout(()=>{
        var r = list[i]
        var node = this.list.children[i];
        if (!node) {
            node = this.getItem();
            this.list.addChild(node);
        }
        cc.find('rank', node).getComponent(cc.Label).string = i + 1;
        cc.find('name', node).getComponent(cc.Label).string = r.nickname;
        cc.find('winOrLose', node).getComponent(cc.Label).string = r.bigwin;
        finished++;
        if (finished == list.length) {
            console.log("update,time:" + (new Date().getTime() - time));
        }
    }, i*20);
}

Find 和 getComponent是比较耗性能的(猜测跟Unity差不多,没有试验过),尽量不这么用

性能问题最好 profile 一下
我猜这里这么慢的原因是设置了 string

        this._index = 0;
        this._datas = datas;

        this.schedule(function () {
            if (this._index >= this._datas.length) {
                return;
            }
            var i = this._index;
            var r = this._datas[i]
            var node = this.list.children[i];
            if (!node) {
                node = this.getItem();
                this.list.addChild(node);
            }
            cc.find('rank', node).getComponent(cc.Label).string = i + 1;
            cc.find('name', node).getComponent(cc.Label).string = r.nickname;
            cc.find('winOrLose', node).getComponent(cc.Label).string = r.bigwin;

            this._index++;
        }, 0, this._datas.length);
```
分享一下我的改法,应该跟setTimeout是差不多的做法。

如果没记错,unity的协程也是在单线程里处理的,只是它把一个集中的N次处理不在同一帧处理,平均分到不同的帧,跟我们这样的优化方法是差不多的。

按cocos官方技术大大的做就OK了,如果要总结一下,可以搭配,schedule,setTimeOut,setInterval,Action等来达到差不多协程的目的。

同时设置大量label会有明显的卡顿感。。。这个引擎团队有优化的方向么

这三行去掉,大概可以节省0.4秒,还需要大概0.6秒。this.getItem()使用的是对象池,在onLoad就已经分配好了,不知道怎么再能优化了。

可以自己写一个 协程管理 反正现在jsb都支持 如果是浏览器的话 就不知道是不是都支持 yield了