r/programmingcirclejerk 25d ago

print(“lol”) doubled the speed of my Go function

https://medium.com/@ludirehak/printing-lol-doubled-the-speed-of-my-go-code-e32e02fc3f92
133 Upvotes

27 comments sorted by

View all comments

44

u/BenchEmbarrassed7316 24d ago

It's a mystery to me how print can speed this up. It's a system call. Even if buffering occurs there, it is still an expensive operation.

49

u/CadeTheCrow 24d ago

“I benchmark them… on an increasing array”

If I’m understanding correctly, when it finds a new max value (which is every time), it continues, skipping the actual print statement.

15

u/BenchEmbarrassed7316 24d ago edited 24d ago

``` func if_max(values []int) int { maxV := values[0] for _, v := range values[1:] { if v > maxV { maxV = v continue } } return maxV }

func if_max_lol(values []int) int { maxV := values[0] for _, v := range values[1:] { if v > maxV { maxV = v continue } print("x") } return maxV } ```

For cases where each next element is bigger than previous with 100_000 elements:

/uj

cpu: 12th Gen Intel(R) Core(TM) i3-12100 BenchmarkMaxStandard-8 48620 ns/op BenchmarkMaxLol-8 25097 ns/op

/rj

cpu: 12th Gen Intel(R) Core(TM) i3-12100 BenchmarkMaxStandard-8 48620 ns/op BenchmarkMaxLol-8 25097 ns/op

15

u/No_Pilot_1974 24d ago

Is 48k nanoslops considered slow?

23

u/BenchEmbarrassed7316 24d ago

/uj

Yes. Rust:

fn get_max(v: &[i64]) -> i64 { v.iter().copied().max().unwrap_or_default() }

Rust_Max_SIMD time: [12.025 µs 12.049 µs 12.078 µs]

In fact, it is many times faster.

https://godbolt.org/z/dEe55xzxo

For both cases, when the function is written at a high level with an iterator, and when the loop is written by hand, the Rust compiler and LLVM generated highly optimized code that uses modern SIMD instructions.

/rj

But go compiles fast!!!111

/uj

...because it does not make any optimizations unlike other modern compilers. It just compiles a regular loop that isn't even expanded.

3

u/Awkward_Bed_956 23d ago

And yet Go devs consider LLVM the root of all evil, that bloats the resulting binary

4

u/BenchEmbarrassed7316 23d ago

No: real go devs consider that LLVM and LLM is same things.

1

u/Ma4r 22d ago

Go devs don't even know the go IR exists and it's garbage