im am writing a simple emulator in go (should i? or should i go back to c?). anyway, i am fetching the instruction and decoding it. at this point i have a byte like 0x81, and i have to execute the right function.
should i have something like this
func (sys *cpu) eval() {
switch opcode {
case 0x80:
sys.add(sys.b)
case 0x81:
sys.add(sys.c)
etc
}
}
or something like this
var fnTable = []func(*cpu) {
0x80: func(sys *cpu) {
sys.add(sys.b)
},
0x81: func(sys *cpu) {
sys.add(sys.c)
}
}
func (sys *cpu) eval() {
return fnTable[opcode](sys)
}
1.which one is better?
2.which one is faster?
also
3.can i declare a function inline?
4.i have a cpu
struct
in which i have the registers etc. would it be faster if i have the registers and all as globals? (without the struct
)
thank you very much.
Fallthrough. In Go, the control comes out of the switch statement immediately after a case is executed. A fallthrough statement is used to transfer control to the first statement of the case that is present immediately after the case which has been executed.
Example: switch case in Golang Println("Tuesday") inside the case is executed. Note: Unlike other programming languages like C and Java, we don't need to use break after every case. This is because in Go, the switch statement terminates after the first matching case.
A switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value(also called case) of the expression.
Fallthrough. A fallthrough statement transfers control to the next case. It may be used only as the final statement in a clause.
I did some benchmarks and the table version is faster than the switch version once you have more than about 4 cases.
I was surprised to discover that the Go compiler (gc, anyway; not sure about gccgo) doesn't seem to be smart enough to turn a dense switch into a jump table.
Update: Ken Thompson posted on the Go mailing list describing the difficulties of optimizing switch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With