小编Ami*_*sef的帖子

为什么DOM读/写操作的微小重新排序会导致巨大的性能差异

以下代码说明了问题,更改读/写顺序会导致执行时间的巨大差异(使用Chrome,Firefox和IE测试):

// read->write->read->write...
function clearSlow(divs){
    Array.prototype.forEach.call(divs, function(div) {
        contents.push(div.clientWidth);
        div.style.width = "10px";
    });
}
// read->read->...->write->write...
function clearFast(divs){
    Array.prototype.forEach.call(divs, function(div) {
        contents.push(div.clientWidth);
    });
    Array.prototype.forEach.call(divs, function(div) {
        div.style.width = "10px";
    });
}
Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子http://jsfiddle.net/Dq3KZ/2/的JSFiddle .

我的结果为n = 100:
慢版本:~35ms
快速版本:~2ms

对于n = 1000:
慢速版本:~2000ms
快速版本:~25ms

我认为这与每种情况下浏览器重排的数量有关.在慢速场景中,每次写入操作都会发生回流.但是,在快速场景中,回流仅在结束时发生一次.但我不确定,我不明白它为什么会这样工作(当操作独立时).

编辑:我使用了InnerText属性而不是clientWidthStyle.Width,在使用谷歌浏览器时我有相同的行为(http://jsfiddle.net/pindexis/CW2BF/7/).但是,当InnerHTML使用时,几乎没有差异(http://jsfiddle.net/pindexis/8E5Yj/).

Edit2:我已经为那些感兴趣的人开启了关于innerHTML/innerText问题的讨论:为什么用innerText替换InnerHTML导致性能下降> 15X

javascript performance firefox dom google-chrome

13
推荐指数
1
解决办法
666
查看次数

为什么用innerText替换InnerHTML导致性能下降> 15X

这个问题来自我之前的帖子,为什么DOM读/写操作的微小重新排序会导致巨大的性能差异.

考虑以下代码:

function clearHTML(divs) {
    Array.prototype.forEach.call(divs, function (div) {
        contents.push(div.innerHTML);
        div.innerHTML = "";
    });
}

function clearText(divs) {
    Array.prototype.forEach.call(divs, function (div) {
        contents.push(div.innerText); //innerText in place of innerHTML
        div.innerHTML = "";
    });
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/pindexis/ZZrYK/

我的测试结果为n = 100:
ClearHTML:~1ms
ClearText:~15ms

对于n = 1000:
ClearHTML:~4ms
ClearText:~1000ms

我在google chrome和IE上测试了代码并得到了类似的结果(Firefox不支持innerText).

编辑: 两个函数之间的差异不是由于innerHTxt函数与innerHTML相比的缓慢造成的,这是肯定的(我尝试删除div.innerHTML =""并获得性能提升),这里发生了奇怪的浏览器重排.

html javascript dom google-chrome

9
推荐指数
1
解决办法
2604
查看次数

使用outb和inb进行低级I/O访问

我很难理解中断是如何工作的.

下面的代码初始化可编程中断控制器

  #define PIC0_CTRL 0x20    /* Master PIC control register address. */
  #define PIC0_DATA 0x21    /* Master PIC data register address. */

  /* Mask all interrupts*/
  outb (PIC0_DATA, 0xff);

  /* Initialize master. */
  outb (PIC0_CTRL, 0x11); /* ICW1: single mode, edge triggered, expect ICW4. */
  outb (PIC0_DATA, 0x20); /* ICW2: line IR0...7 -> irq 0x20...0x27. */
  outb (PIC0_DATA, 0x04); /* ICW3: slave PIC on line IR2. */
  outb (PIC0_DATA, 0x01); /* ICW4: 8086 mode, normal EOI, non-buffered. */

  /* Unmask …
Run Code Online (Sandbox Code Playgroud)

c io assembly interrupt hardware-port

5
推荐指数
1
解决办法
1万
查看次数

没有在C中获得分段错误

这是c代码:

char **s;
s[334]=strdup("test");
printf("%s\n",s[334]);`
Run Code Online (Sandbox Code Playgroud)

我知道strdup会进行"test"的分配,但是我们将把指针放到字符串"test"的情况下[334]没有分配,但是,这段代码的作用就像一个魅力

c segmentation-fault

2
推荐指数
1
解决办法
197
查看次数