11
submitted 2 weeks ago by tracyspcy@lemmy.ml to c/rust@lemmy.ml

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/tracyspacy/fli/commit/a87a98be77cc1972a53e6399716a227d1135e76b

details: https://pastebin.com/qJdTw49n

top 4 comments
sorted by: hot top new old
[-] tracyspcy@lemmy.ml 2 points 2 weeks ago

Folks , if you have any thoughts , please do share

[-] tracyspcy@lemmy.ml 1 points 2 weeks 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.

[-] TehPers@beehaw.org 2 points 2 weeks ago

This was also posted here: https://programming.dev/post/52906691

Just FYI if you want to follow that discussion.

[-] tracyspcy@lemmy.ml 2 points 2 weeks ago

thank you! Oh. it seems user is blocked on lemmy.ml or something like that, so i cannot participate in this discussion or even see the post and answers within my instance.

Since I cannot reply where, you can post my reply if you wish: 2 points:

  1. more complex closure and not only control flow, it can be simple arithmetic expression as well, results in actually smaller assembly on arm-unknown-linux-gnueabihf target.
  2. I don't think the loop unrolling plays a big role here. sort_unstable_by() is using quicksort and I suspect that complex closure was outlined to a separate fn, and not copied to quicksort anymore.
this post was submitted on 02 Jul 2026
11 points (100.0% liked)

Rust Programming

9324 readers
12 users here now

founded 7 years ago
MODERATORS