Why is this closure slower the second time it is used?

One common theme I see between this test case and your other test case is that you're testing using top-level code, which is going to get emitted using global variables, and this likely leads to less predictable optimization behavior than wrapping the test case in a function. From @dabrahams' comment it sounds like this might be at play here too. You might get more predictable behavior, more representative of what you'd see in real code, writing these tests as functions instead of as top-level code. There's no good fundamental reason for top-level code to be different from a function, so it's still great that you're uncovering these issues, but if you're getting frustrated trying to understand the optimizer's behavior, avoiding top-level code might at least eliminate one variable for now.

2 Likes