简体   繁体   中英

Strange optimization? in `libuv`. Please explain

The libuv contains next code in core.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;

What does this mean? Is it some kind of optimization? Why they did not simply assign 0?

Yes, just like the comment says. In case the flag is already 0, there is no need to write any data to the memory, thus avoiding a possible eviction of present data in the cache and replacing it with 0 for the flag. This will provide added value only in extremely time-critical applications.

I would argue this optimization is bad. For example, on gcc with -O3 it gives following code:

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

As you see, there is no conditional move, but a branch. And I am sure, branch misprediction is far worse than dirtying the cache line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM