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

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

问题描述

我正在做一些编码,在这里我必须编写这种代码:

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天全站免登陆