美文网首页
假象,为什么遍历次数多反而耗时少?

假象,为什么遍历次数多反而耗时少?

作者: 二石兄 | 来源:发表于2017-11-28 00:10 被阅读74次

    编程竞赛 - 数组父子关系的转换(完成)
    坠入莱茵河@编程竞赛 - 数组父子关系的转换

    let array = [
        ['1', '', 'title1', 1, 2, 3],
        ['2', '', 'title2', 4, 5, 6],
        ['11', '1', 'title3', 7, 8, 9],
        ['21', '2', 'title4', 10, 11, 12],
        ['22', '2', 'title5', 13, 14, 15],
        ['111', '11', 'title6', 16, 17, 18],
        ['211', '21', 'title7', 19, 20, 21],
        ['2111', '211', 'title8', 22, 23, 24]
    ];
    
    class ParseArray {
        constructor(inputArray) {
            this.inputArray = inputArray
            this.outputArray = [{
                "sub_data": []
            }]
            this.loopLength = 0
        }
        loop(pId, items) {
            this.inputArray.forEach((item, idx) => {
                this.loopLength++
                    if (item[1] === pId) {
                        items.push({
                            main_data: item.slice(2),
                            sub_data: []
                        })
                        delete this.inputArray[idx] // 录入后删掉该条数据 可降低循环次数
                        this.loop(item[0], items[items.length - 1].sub_data)
                    }
            })
        }
    }
    
    console.time("loop")
    let val = new ParseArray(array.slice())
    val.loop('', val.outputArray[0].sub_data)
    console.log(JSON.stringify(val.outputArray))
    console.log(val.loopLength) // => 26
    console.timeEnd("loop")     // => loop: 0.2919921875ms
    
    function convert_table_data_with_level(data, parent_node = "") {
        var level_1_data = [],
            new_data = [];
        for (var i = 0, len = data.length; i < len; i++) {
            data[i][1] === parent_node ? level_1_data.push(data[i]) : new_data.push(data[i]);
            recursionLength++;
        }
    
        return level_1_data.map(function(arr) {
            parent_node = arr[0];
            return {
                main_data: arr.splice(2, arr.length - 2),
                sub_data: convert_table_data_with_level(new_data, parent_node)
            }
        });
    }
    
    console.time("recursion")
    let recursionLength = 0;
    let data_with_level = convert_table_data_with_level(array, '')
    console.log(JSON.stringify(data_with_level))
    console.log(recursionLength) // 42
    console.timeEnd("recursion") // => recursion: 0.098876953125ms
    

    相关文章

      网友评论

          本文标题:假象,为什么遍历次数多反而耗时少?

          本文链接:https://www.haomeiwen.com/subject/tanjbxtx.html