Skip to content

Performance issue re: simple loop

The runtime of the following code actually decreases if the number 2147483647 (2^31^-1) is increased to 2147483648 (2^31^). In addition, adding "module Main where" at the top of the file improves performance to the fast case regardless of what number is picked.

f n = go 1 0 where
  go i c = if i == n then c + i else go (i+1) (c+i)

main = print $ f (2147483647 :: Int) 

I've attached two dumps from ghc-core, core7 is the 2147483647 case and core8 is the 2147483648 case, however the main differences are below:

2147483647 case:

_c3Qg:
	cmpq $2147483647,%r14
	jne _c3Q9
_c3Qa:
	leaq 2147483647(%rsi),%rbx
	jmp *(%rbp)
_c3Q9:
	addq %r14,%rsi
	incq %r14
	jmp _c3Qg

2147483648 case:

_c3Qg:
	movl $2147483648,%eax
	cmpq %rax,%r14
	jne _c3Q9
_c3Qa:
	movl $2147483648,%eax
	movq %rsi,%rbx
	addq %rax,%rbx
	jmp *(%rbp)
_c3Q9:
	addq %r14,%rsi
	incq %r14
	jmp _c3Qg

Despite the extra instructions, the latter approach seems faster for my PC.

Edited by clinton
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information