tinygo-org / tinygo

Go compiler for small places. Microcontrollers, WebAssembly (WASM/WASI), and command-line tools. Based on LLVM.
https://tinygo.org
Other
14.72k stars 858 forks source link

Optimize `[]byte` to `string` conversions #4289

Open lpereira opened 3 weeks ago

lpereira commented 3 weeks ago

This enables the optimization of functions such as "bytes.Equal()", which is currently implemented as:

func Equal(a, b []byte) bool { return string(a) == string(b) }

Which causes allocations and copies in TinyGo, but not in Big Go.

Since we can prove that neither conversions will escape in this case, we can convert the calls to runtime.stringFromBytes() to an inlined version of it that doesn't allocate or copies the original string.

This is a draft PR, because, although I can verify that the relevant calls to the runtime alloc calls are removed from the final binary in a simple test program, make test is failing. I'd like some help here to understand what's happening.

Another thing that I didn't have time today to check was why isReadOnly() was returning false for my test program; I'll pick this up on Monday to take a closer look, but for now, I'm omitting the call here, which is most likely why make test isn't happy.

Closes: #4045 CC: @aykevl @dgryski

lpereira commented 3 weeks ago

Rebased and pushed a new version, that also improves the read-only checks to catch more usages. I still need to fine-comb the table I added for this; however, local tests (make tinygo-test-wasi) seem to be working, but I don't have all the dependencies for things other than WASM building, so I'll wait for the CI to see if I need to fix something unexpected.