奇怪的优化?在“ libuv”中.请解释

Strange optimization? in `libuv`. Please explain

本文关键字:libuv 解释 优化      更新时间:2023-10-16

libuvcore.c:uv_run()

中包含下一个代码
/* The if statement lets the compiler compile it to a conditional store.
 * Avoids dirtying a cache line.
 */
if (loop->stop_flag != 0)
    loop->stop_flag = 0;

这是什么意思?是某种优化吗?为什么他们不简单地分配0?

是的,就像评论所说的那样。如果标志已经为0,则无需将任何数据写入内存,从而避免了缓存中当前数据的可能驱逐并用0代替标志。这仅在极端时间的应用程序中提供附加的值。

我会说这种优化是不好的。例如,在带有-O3的GCC上,它提供以下代码:

foo():
        movl    stop_flag(%rip), %eax
        testl   %eax, %eax
        je      .L3
        movl    $0, stop_flag(%rip)
.L3:
        ret
stop_flag:
        .zero   4

如您所见,没有有条件的移动,而是分支。而且我敢肯定,分支错误预测远比弄脏缓存线更糟糕。