哪个更快?比较还是赋值? [英] Which is faster? Comparison or assignment?

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

问题描述

我正在做一些编码,我必须在其中编写此类代码:

I'm doing a bit of coding, where I have to write this sort of code:

if( array[i]==false )
    array[i]=true;

不知道是不是应该改写为

I wonder if it should be re-written as

array[i]=true;

这就提出了一个问题:比较是否比赋值更快?

This raises the question: are comparisions faster than assignments?

语言与语言之间的差异如何?(例如java和cpp之间的对比)

What about differences from language to language? (contrast between java & cpp, eg.)

注意:我听说过早的优化是万恶之源".我认为这不适用于这里:)

推荐答案

好吧,既然您说您确定这很重要,那么您应该编写一个测试程序并进行测量以找出差异.

Well, since you say you're sure that this matters you should just write a test program and measure to find the difference.

如果对分配在内存中分散地址的多个变量执行此代码,则比较可以更快.通过比较,您只会将数据从内存读取到处理器缓存,并且如果您在缓存决定刷新该行时不更改变量值,它将看到该行未更改并且无需将其写回到内存.这可以加快执行速度.

Comparison can be faster if this code is executed on multiple variables allocated at scattered addresses in memory. With comparison you will only read data from memory to the processor cache, and if you don't change the variable value when the cache decides to to flush the line it will see that the line was not changed and there's no need to write it back to the memory. This can speed up execution.

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

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