AdventOfCode: Haskell solution faster than C?

My Haskell solution for Day 3 takes 16ms, compared to my C solution taking 140ms. While my Haskell brain is happy, I’m curious what optimizations Haskell is making here. I don’t see any obviously lazy improvements.

Haskell: advent-of-code/2025/Day03.hs at main · brandonchinn178/advent-of-code · GitHub

C: advent-of-code/2025/Day03.c at main · brandonchinn178/advent-of-code · GitHub

2 Likes

The C solution is linear and the Haskell solution is NlogN. So I doubt it’s anything to do with the algorithm and optimization.

My suspicion is that all the dynamic allocation/lack of IO buffering with getLine makes c code slower (in Haskell you get the entire file and then go straight to processing).

For an apples to apples comparison I’d do the same line by line IO. Line by line input is expensive cause you make system calls on every iteration.

2 Likes

Never mind, it’s an issue with my timer somehow…

3 Likes

Out of curiosity what was the issue and what is the speed difference after fixing the timer?

I ran gcc every time, which produces a new executable every time, and the first run of an executable always has overhead (cold cache, antivirus, etc.). The haskell executable didn’t have this problem because stack script knows to not regenerate the executable if the src files didn’t change. Fix was to emulate make and check if src file was modified after executable file.

New speed is something like 1.7ms to 16ms

1 Like