obvious variable types [1] instead of stating them explicitly [2] all the time is a good practice.
[1] a := 5
[2] var a int = 5
However, won't it slow down the compiler in the long run?
Because to my understanding, type inference is one of the reasons why interpreted languages are relatively slow 🤔
Short answer: not really. Long answer: actually, why not run a benchmark? 😀 generate code with lots and lots of variable declarations and measure the compilation time & cpu/memory usage
Explicitly stating the type does not skip type inference. Some type info still has to be inferred from the value you're assigning to check if it is compatible with the type. Perhaps stating the type explicitly is slower as it forces a compatibility check (which is skipped with inference), but that's just speculation.
best way to find out is to measure
I really don't wanna get into a fight but interpreted languages are slow not because of just lack of types, they are slow because they don't have machine code as a binary to run, a runtime will parse them while they are being executed generally... as for type inference in Go there are costs but explicit types don't matter they don't add much to perf because they almost always generate the same machine code in Go... because types on assignment are always inferred before compilation happens. Worst case, your compilation speed is slightly slower(milliseconds if at all), Note: I haven't looked at how the Go compiler handles types(my complaints for it's practices aside), I don't see a reason for it's inference to be much slower. But the code generated is the same, so you should not worry... If you are using pointers and loose types and maybe a lot of casts then yes you are very likely hurting performance, otherwise don't care that much.
btw from what I know, Go doesn't really have a heavy type system at all, it just takes the type of right hand side and uses that on the left hand side at compile time. Finally generated code is exactly the same hence. Some one with more experience with Go internals or something can feel free to correct...
this means, [1] a := 5 [2] var a int = 5 1 and 2 are the exact same just look different
it's not at all because of type inference that interpreted languages are slow and having go compiler figure out the type of variable by type of value is pretty much zero cost compared to the rest of type checking
Обсуждают сегодня