泡泡饭

导航

cells[index],children[index]效率问题

看到以下代码,并做了测试:

<body>
<input type=button onclick=hideCol(1) value='隐藏第 2 列'>
<input type=button onclick=showCol(1) value='显示第 2 列'>
<div id=tableBox></div>
<script>

//--------------------------------------------------------
// 时间转为时间戳(毫秒)
function time2stamp(){var d=new Date();return Date.parse(d)+d.getMilliseconds();}

//--------------------------------------------------------
// 创建表格
function createTable(rowsLen)
{
    var str = "<table border=1>" +
                "<thead>" +
                    "<tr>" +
                        "<th width=100>col1<\/th>" +
                        "<th width=200>col2<\/th>" +
                        "<th width=50>col3<\/th>" +
                    "<\/tr>" +
                "<\/thead>" +
                "<tbody>";

    var arr = [];
    for (var i=0; i<rowsLen; i++)
    {
        arr[i] = "<tr><td>" + i + "1<\/td><td>" + i + "2</td><td>" + i + "3<\/td></tr>";
    }
    str += arr.join("") + "</tbody><\/table>"; // 用 join() 方式快速构建字串,速度极快
    tableBox.innerHTML = str; // 生成 table
}

//--------------------------------------------------------
// 隐藏/显示指定列
function hideCol(colIdx){hideOrShowCol(colIdx, 0);}
function showCol(colIdx){hideOrShowCol(colIdx, 1);}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function hideOrShowCol(colIdx, isShow)
{
    var t1 = time2stamp(); //
    var table = tableBox.children[0];
    var rowsLen = table.rows.length;
    var lastTr = table.rows[0];
    for (var i=0; i<rowsLen; i++)
    {
        var tr = table.rows[i];
        tr.children[colIdx].style.display = isShow ? "" : "none";
    }
   
    var t2 = time2stamp();
    alert("耗时:" + (t2 - t1) + " 毫秒");
}

//--------------------------------------------------------
createTable(1000); // 创建千行表格

</script>

然后对function hideOrShowCol对了以下修改

function hideOrShowCol(colIdx, isShow)
{
    var t1 = time2stamp(); //
    var table = tableBox.children[0];
    var rowsLen = table.rows.length;
    var lastTr = table.rows[0];
    for (var i=0; i<rowsLen; i++)
    {
        var tr = table.rows[i];
        tr.cells[colIdx].style.display = isShow ? "" : "none";
    }
   
    var t2 = time2stamp();
    alert("耗时:" + (t2 - t1) + " 毫秒");
}

 

做测试:速度上要慢10%以上

posted on 2009-03-27 15:51  泡泡饭  阅读(388)  评论(1编辑  收藏  举报