功能表与golang中的开关 [英] table of functions vs switch in golang

查看:135
本文介绍了功能表与golang中的开关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个简单的模拟器(我应该吗?还是应该回到c?)。
无论如何,我正在获取指令并对其进行解码。在这一点上,我有一个像0x81字节,我必须执行正确的功能。



我应该有这样的东西



$ $ p $ func(sys * cpu)eval(){
switch opcode {
case 0x80:
sys.add(sys.b)
case 0x81:
sys.add(sys.c)
etc
}
}

或类似的东西

  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>哪一个更好?

2哪个更快?< br>
也可以

3.我可以声明函数内联?

4.i有一个 cpu struct 其中我有寄存器等,如果我有寄存器和所有全局变量会更快? (没有 struct

非常感谢。

解决方案


  1. 第一个版本对我来说更好看,YMMV。 >基准。取决于编译器在优化方面的优势。如果编译器没有足够努力去优化,跳转表版本可能会更快。

  2. 取决于你声明函数的定义一致。 Go只能在顶层声明和定义函数/方法。但是函数是Go中的第一类公民,所以可以有变量/参数/返回值和函数类型的结构化类型。在所有这些地方,函数文字可以[也]分配给变量/字段/元素。 ..
  3. 可能。我仍然建议不要将cpu状态保存在全局变量中。一旦你可能决定仿效多核,这将是受欢迎的; - )



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.

解决方案

  1. The first version looks better to me, YMMV.

  2. Benchmark it. Depends how good is the compiler at optimizing. The "jump table" version might be faster if the compiler doesn't try hard enough to optimize.

  3. Depends on your definition of what is "to declare function inline". Go can declare and define functions/methods at the top level only. But functions are first class citizens in Go, so one can have variables/parameters/return values and structured types of function type. In all this places a function literal can [also] be assigned to the variable/field/element...

  4. Possibly. Still I would suggest to not keep the cpu state in a global variable. Once you possibly decide to go emulating multicore, it will be welcome ;-)

这篇关于功能表与golang中的开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆