go-app icon indicating copy to clipboard operation
go-app copied to clipboard

Dead code elimination in Example

Open kidandcat opened this issue 1 year ago • 1 comments

Because Go compiler has dead code elimination, if we encapsulate the backend code in this if, as it is based on a constant value, the compiler will remove all code related to what's inside that if when compiling for wasm, leading to considerable size reduction.

(In my playground app it reduces size from 21MB to 17MB uncompressed)

kidandcat avatar Jun 02 '24 06:06 kidandcat

This is very interesting We use build tags for all larger project to separate backend and frontend code, so this has no effect. But I tested it with https://github.com/oderwat/go-guess-the-number-app, and it reduces app.wasm from 16 MB to 5.1 MB, which is very cool.

	if !app.IsServer {
		return // let dead code elimination optimize the frontend code
	}

P.S.: I tried to use the same concept on our much larger apps and found that it does reduce the size also considerably but using build tags reduces the size even more. In one example with a private project (AI frontend) of mine I get 21 MB without any optimization, 8.3 MB using app.IsServer in main.go and 6.8 MB with our code separation using the WASM build flag.

P.P.S.: Using the build tag is demonstrated here: https://github.com/oderwat/go-nats-app which recently was update to V10.

oderwat avatar Jun 02 '24 10:06 oderwat