joshlf
joshlf

Reputation: 23537

How can I defeat the Go optimizer in benchmarks?

In Rust, you can use the black_box function to force the compiler to

  1. assume that the function's argument is used (forcing it not to optimize away code that generates that value)
  2. not be able to inspect how its return value is produced (preventing it from doing constant-folding and other such optimizations).

Is there a similar facility in Go (to accomplish either task)?

Upvotes: 0

Views: 547

Answers (2)

Volker
Volker

Reputation: 42433

Is there a similar facility in Go (to accomplish either task)?

No.

If you want to use a result: Assign to an exported global.

Upvotes: 2

Veedrac
Veedrac

Reputation: 60117

I believe runtime.KeepAlive is recommended, as per the following Github issue. Unfortunately, it's unclear whether anything exists for function arguments, or whether KeepAlive is even guaranteed to work.

https://github.com/golang/go/issues/27400

Upvotes: 1

Related Questions