比较昂贵还是比较昂贵? [英] What's more expensive, comparison or assignment?

查看:86
本文介绍了比较昂贵还是比较昂贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始阅读算法,我一直在想,在交易时使用相同类型的原语,哪个是更昂贵的操作,赋值或比较?语言之间的差异是否很大?

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?

推荐答案

微优化几乎总是错误的做法。除非程序运行太慢,否则甚至不要开始运行它,而要使用探查器确定慢速零件的确切位置。

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.

最后,语言通常被编译为机器代码,以及诸如比较和赋值之类的简单操作通常将被编译相同。最大的区别在于CPU的类型。

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.

这篇关于比较昂贵还是比较昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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