通过JS动态添加的DOM元素,性能问题(DIV VS列表框VS C#)

问题描述 投票:-1回答:1

我试着在我的I7与64GB拉姆后续代码。结果让我感到吃惊。有添加元素作为DIV子(2秒),并添加到OPTION列表框(15秒)之间有很大的区别。为什么?

毕竟我disapointed甚至约2秒,DIV版本。我注意到,浏览器只在JS块的最终更新视图。那么,为什么需要更长的时间,然后运行遍历类似集合添加操作?

为了比较的原因,我试图填补的Winform的DataGridView。如果你没有数据表填满它,它需要很长的时间,但是如果你使用的数据表,它是采取什么!

因此,在浏览器中有一种方法来实现这一目标?也是为什么ListBox中是如此缓慢VS列表框。

下面是代码示例。

HTML与JS:

function addListItem()
{
  lst = document.getElementById("lst");

  for(let c=0;c<30000;c++){
    n=document.createElement("option");
    n.text="Dynamic item " + c;    
    lst.options.add(n);  
  }  
}


function addTmpl()
{
  ph = document.getElementById("place_holder");
  t = document.getElementById("template");
  
  for(let c=0;c<30000;c++){
    n = t.cloneNode(true);
    n.id = "item";
    n.style.visibility="visible";
    ph.appendChild(n);  
  }
}

  
<div id="ss">
  <button onclick="addListItem()">Fill list</button>
  <button onclick="addTmpl()">Clone div</button>
</div>

<select id="lst" size="13" style="width:250"> 
  <option>Static item</option>
</select>


<div id="place_holder" style="background-color:yellow;margin:10px">Div Place holder</div>

<div id="template" style="visibility:hidden">Div item</div>

<script src="aa.js"></script>

这里的C#代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class frmTestAddingItemsPrformance : Form
    {
        public frmTestAddingItemsPrformance()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable t = new DataTable();
            t.Columns.Add("Column1");


            for (int i = 0; i < 30000; i++)
            {
                DataRow r = t.NewRow();
                r[0] = i.ToString();
                t.Rows.Add(r);                
            }
            dataGridView1.DataSource = t;
        }
    }
}
javascript html
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.