Rust sort_unstable_by with more complex closure unexpectedly shrunk binary

3 months ago by tracyspcy to c/rust

Crossposted from https://lemmy.ml/post/49521856

Thing I stumbled upon:

I added boolean argument & if statement inside sort_unstable_by closure:

//from
|&a, &b| compare(a, b) 

//to
|&a, &b| if is_reverse { compare(b, a) } else { compare(a, b) }

I expected binary to grow slightly, but actually ca 1KB smaller.

I dug into & found that the reason is: quicksort fn became 980 bytes smaller.

Why? Not sure. Inlining looks same, quicksort just has fewer instructions.

target: arm-unknown-linux-gnueabihf

commit: https://github.com/...

details: https://pastebin.com/qJdTw49n

tracyspcy 1 point 3 months ago

Folks , if you have any thoughts , please do share

path: 0 24561986, hotness: undefined, score: 1, children: 1
tracyspcy 1 point 3 months ago

While post body contains control flow, it can be simple arithmetic operation instead and it will lead to the similar result, so not the control flow itself causing this. It seems more complex closure blocks some optimizations here, thus quicksort having less instructions. I suspect that complex closure was outlined to a separate fn, and not copied to quicksort anymore.

path: 0 24561986 24566052, hotness: undefined, score: 1, children: 0
rust
rust

@lemmy.ml

login for more options
9402
397
129

go to feed...