比较和分配哪个更昂贵?

发布于 2024-07-14 22:57:32 字数 149 浏览 3 评论 0原文

我已经开始阅读算法并且我一直想知道,在处理原语时相同类型,赋值和比较哪个操作成本更高? 不同语言之间的差异很大吗?

I've started reading Algorithms and I keep wondering, when dealing with primitives of the same type, which is the more expensive operation, assignment or comparison? Does this vary a great deal between languages?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橙幽之幻 2024-07-21 22:57:32

你怎么认为?

在最低级别,一个执行两次读取,另一个执行一次读取和一次写入。

但你为什么要真正关心呢? 您不应该关心这个级别的性能。 针对 Big-O 进行优化

What do you think?

At the lowest level one does two reads, the other does a read and a write.

But why should you really care? You shouldn't care about performance at this level. Optimize for Big-O

怀中猫帐中妖 2024-07-21 22:57:32

微观优化几乎总是错误的做法。 甚至不要开始它,除非程序运行得太慢,并且您使用分析器来准确确定慢速部分的位置。

完成此操作后,我的建议是考虑改进代码和数据局部性,因为缓存未命中几乎肯定比次优指令更糟糕。

完成后,在相当奇怪的情况下,您可以使用基于分配或基于比较的方法,尝试两种方法并计时。 微观优化是一种数字游戏。 如果数字不够好,请找出原因,然后验证您所做的事情是否确实有效。

那么,你说的比较是什么意思呢? 条件跳转会给任何现代处理器带来问题,但不同的处理器会做不同的事情,并且不能保证任何给定的处理器都会减慢速度。 另外,如果其中任何一个导致缓存未命中,那么无论如何它都可能是较慢的。

最后,语言通常被编译为机器代码,并且像比较和赋值这样的简单事情通常会被编译为相同的代码。 最大的区别在于 CPU 的类型。

Micro-optimization is almost always the wrong thing to do. Don't even start on it unless the program runs too slowly, and you use a profiler to determine exactly where the slow parts are.

Once you've done that, my advice is to see about improving code and data locality, because cache misses are almost certainly worse than suboptimal instructions.

That being done, in the rather odd case that you can use either an assignment-based or comparison-based approach, try both and time them. Micro-optimization is a numbers game. If the numbers aren't good enough, find out why, then verify that what you're doing actually works.

So, what do you mean by a comparison? Conditional jumps cause problems to any vaguely modern processor, but different processors do different things, and there's no guarantee that any given one will slow things down. Also, if either causes a cache miss, that's probably the slower one no matter what.

Finally, languages are normally compiled to machine code, and simple things like comparisons and assignments will normally be compiled the same. The big difference will be the type of CPU.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文