Hacker News new | ask | show | jobs
by IshKebab 4098 days ago
Totally off-topic, but I was curious if the recursive Rust `sum` function is actually optimised correctly.

Code:

    fn sum(l: &[i64]) -> i64 {
        match l {
            [] => 0,
            [x, xs..] => x + sum(xs)
        }
    }
Assembly:

  _ZN3sum20hf66fc5855a7cf5fc3aaE:
	.cfi_startproc
	cmpq	%fs:112, %rsp
	ja	.LBB2_2
	movabsq	$24, %r10
	movabsq	$0, %r11
	callq	__morestack
	retq
  .LBB2_2:
	pushq	%rbx
  .Ltmp10:
	.cfi_def_cfa_offset 16
	subq	$16, %rsp
  .Ltmp11:
	.cfi_def_cfa_offset 32
  .Ltmp12:
	.cfi_offset %rbx, -16
	movq	8(%rdi), %rcx
	xorl	%eax, %eax
	testq	%rcx, %rcx
	je	.LBB2_4
	movq	(%rdi), %rax
	decq	%rcx
	movq	(%rax), %rbx
	addq	$8, %rax
	movq	%rax, (%rsp)
	movq	%rcx, 8(%rsp)
	leaq	(%rsp), %rdi
	callq	_ZN3sum20hf66fc5855a7cf5fc3aaE
	addq	%rbx, %rax
  .LBB2_4:
	addq	$16, %rsp
	popq	%rbx
	retq
So... no.
1 comments

You might get better optimizations if you make it tail recursive (LLVM probably gets some of these). ie:

    fn sum_tail(v : i64, l: &[i64]) -> i64 {
        match l {
            [] => v,
            [x, xs..] => sum(v + x, xs)
        }
    }