返回错误代码比使用输出参数慢吗?

huangapple go评论110阅读模式
英文:

Is returning with error code slower than out parameter?

问题

这个问题涉及到Go和C#,所以比较应该涉及到当前的实现——我更多地是在寻找理论上的证据,比如最坏情况下快速排序的性能是...。

在很多关于Go的地方,我看到了一个返回元组的函数,其中最后一个元素是错误代码。而在C#中,通常是使用TryXXX模式,最后一个参数是out

现在我想知道哪种方式的性能更好(再次强调,从理论的角度来看——如果你能够以最佳方式实现它,结果会是什么)。

也许这是一种天真的想法,但是使用元组的方式我看到了内存分配的问题,每次调用函数都需要进行内存分配,无论如何。而使用out参数,你可以在函数外部分配内存,所以即使调用函数数百万次,成本也是零(嗯,除了复制一些数据之外)。

因此,out应该是性能更好的选择,对吗?或者有没有一种方法可以实现元组传递来匹配out?或者我完全错了?

英文:

This issue touches Go and C# so the comparison would deal with current implementations -- I am rather looking for theoretical evidence, something like quick sort in worst case performance is...

In many places dedicated to Go I saw a function that returns a tuple, with last element being an error code. In C# it is rather TryXXX pattern with last out parameter.

Now I wonder which one is better performer (once again, from theoretical standpoint -- meaning if you could implement it at best, what would be the outcome).

Maybe naive thinking, but with tuple approach I see memory allocation problem, you have to do it each time the function is called, no matter what. With out parameter you allocate memory outside the function, so then even if you call a function millions times, the cost is zero (well, except for copying some data).

out then should be a better performer, correct? Or is there some way to implement tuple passing to match out? Or am I completely wrong?

答案1

得分: 1

当前Go套件(gc)实现多返回值的方式与参数的传递方式相同,即通过堆栈传递返回值。在这一点上没有进行内存分配(假设堆栈大小足够,这是另一回事)。考虑到C#中的out参数需要进行分配,我会说Go的方法会更快,但不是因为方法本身,而是因为非原始数据类型在C#中是在堆上分配的,而在Go中,程序员可以选择将其保留在堆栈上。

如果仅考虑参数传递与多返回值,性能影响将不存在,因为两者都表示对堆栈的推入/弹出操作。

英文:

The way multiple return values are implemented by the current Go suite (gc) the return values are passed the same way parameters are, which are on stack. There is no memory allocation at that point (Assuming the stack size was sufficient, which is another matter). Considering the out parameter in C# would need to be allocated, I'd say the Go approach would be faster but not because of the approach in itself but by the fact that non-primitive data types are heap allocated in C# whereas in Go the programmer can choose to keep it on stack.

If we consider simply the parameter passing versus the multiple return value, the performance impact would be non-existant since both represent a push/pop on the stack.

huangapple
  • 本文由 发表于 2014年3月18日 22:04:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/22481761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定