性能:生成展平的父子ID列表

时间:2014-04-18 21:48:26

标签: javascript dom parent-child circular-dependency on-the-fly

我正在寻找一种更好的方法来生成亲子关系图;基于特定的id模式。

要求void 0 === cache[parent][child]的速度更快;预期的结果:

    {
      uuid_1: {uuid_2: {}}
      uuid_2: {uuid_3: {}, uuid_4: {}}
      uuid_3: {}
      uuid_4: {}
    }

HTML结构:

    <html id="uuid-1">
        <body id="uuid-2">
            <somewhere>
                <whatever id="uuid-3" />
            </somewhere>
            <foo id="uuid-4" />
        </body>
    </html>

_fetch()

    <1> // register as init
        <2> // register as child of 1
            <3>
                <4 /> // register as child of 2
            </3>
            <5 /> // register as child of 2
        </2>
    </1>

解析~1300个元素(大菜单结构)找到我的~50个uuids。

使用jQuery尝试1:

_fetch: function(element, factoryName)
{
    var a = {}, l = 0, t = this, f = function(el, n)
    {
        if(!a[n]) a[n] = {};

        var e = $(el), test = $('[id^="uuid-"]', e);

        if(!test.length)
            return;

        e.children().each(function()
        {
            var u = $(this), id = u.attr('id'), q;

            // anonymous element: no class defined
            if(!(id && 'uuid-' === id.slice(0x00, 0x05)))
            {
                f(this, n); // continue with current name
                return;
            }

            l++;
            q = $.T.util.uuidFromId(id);
            $.T.__dict[q] = '#' + id;

            a[n][q] = {};
            // comment in/out
            f(this, q);
        });

    }

    f(element, factoryName);
    return a;
}

使用黄色JS尝试2:

    ..., g = function(n, p)
    {
        var r = [];
        for(var d = (p || document).getElementsByTagName('*'), i = 0, l = d.length; i < l; i++)
            d[i].getAttribute(n) && r.push(d[i]);
        return r;
    },
f = function(el, n)
{
    var z = el.children.length, y = 0;
    if(!a[n]) a[n] = {};

    if(z && g('id', el)) for(; y < z; y++)
    {
        var u = el.children[y], id = u.getAttribute('id'), q;

        if(!(id && 'uuid-' === id.slice(0x00, 0x05)))
        {
            f(u, n);
            continue;
        }

        l++;
        $.T.__dict[q = $.T.util.uuidFromId(id)] = '#' + id;
        a[n][q] = {};

        // it's irrelevant to fetch the full html or a sequence by constructor
        //f(u, q);
    }
}

我的问题是: 如何以更快的方式收集DOM元素作为平面表示;喜欢上面的映射?我目前的解决方案非常滞后。

OT: 基于map的上下文x对话框:

    <baz><alice><bob><bobchild/></bob></alice><foo />

    alice._init:
       before init children of bob
         tell foo 'go away'
       before init bob                // context: no bob
         after init children of alice //          && alice without children
            after init baz            //          && baz not ready -> no hello
               tell baz 'hello'

1 个答案:

答案 0 :(得分:1)

我仍然不太确定我知道你要做什么,但这是我知道走路DOM树并积累父/子信息的最快方式,就像你做的那样构建您希望最终得到的数据结构:

var treeWalkFast = (function() {
    // create closure for constants
    var skipTags = {"SCRIPT": true, "IFRAME": true, "OBJECT": true, 
        "EMBED": true, "STYLE": true, "LINK": true, "META": true};

    return function(parent, fn, allNodes) {
        var parents = [];
        var uuidParents = [];
        parents.push(parent);
        uuidParents.push(parent);
        var node = parent.firstChild, nextNode, lastParent;
        while (node && node != parent) {
            if (allNodes || node.nodeType === 1) {
                if (fn(node, parents, uuidParents) === false) {
                    return(false);
                }
            }
            // if it's an element &&
            //    has children &&
            //    has a tagname && is not in the skipTags list
            //  then, we can enumerate children
            if (node.nodeType === 1 && node.firstChild && !(node.tagName && skipTags[node.tagName])) {
                // going down one level, add this item to the parent array
                parents.push(node);
                if (node.id && node.id.substr(0, 5) === "uuid-") {
                    uuidParents.push(node);
                }
                node = node.firstChild;
            } else  if (node.nextSibling) {
                // node had no children so going to next sibling
                node = node.nextSibling;
            } else {
                // no child and no nextsibling
                // find parent that has a nextSibling
                while ((node = node.parentNode) != parent) {
                    lastParent = parents.pop();
                    if (lastParent === uuidParents[uuidParents.length - 1]) {
                        uuidParents.pop();
                    }
                    if (node.nextSibling) {
                        node = node.nextSibling;
                        break;
                    }
                }
            }
        }
    }
})();

var objects = {uuid_1: {}};
treeWalkFast(document.documentElement, function(node, parents, uuidParents) {
    if (node.id && node.id.substr(0, 5) === "uuid-") {
        var uuidParent = uuidParents[uuidParents.length - 1];
        if (!objects[uuidParent.id]) {
            objects[uuidParent.id] = {};
        }
        objects[uuidParent.id][node.id] = {};
        objects[node.id] = {};
    }
});

此处的演示演示:http://jsfiddle.net/jfriend00/yzaJ6/

这是我为this answer撰写的treeWalkFast()函数的改编。