这是更快? ++ + =或x + 1 [英] Which is faster? ++, += or x + 1?

查看:200
本文介绍了这是更快? ++ + =或x + 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#(这个问题也适用于类似的语言,如C ++),我试图找出递增最快,最有效的方式。它不只是一个或两个的增量,在我的游戏,每秒它像300的增量。相机像屏幕是递增的速度和我的RPG字符位置上的每一个角色的框架,偏移等。所以我在想,什么样的方式是最有效的?例如,对于递增5 Y_POS 的每一个动作,我可以做的:

1。

  Player.YPos + = 5;
 

2。

  Player.YPos = Player.YPos + 5;
 

3。

 的for(int i = 0;我小于5;我++)
{
    Player.YPos ++;
}
 

这是最有效的(和最快的)?

解决方案

(回答具体到C#和C ++可能显著有所不同。)

1和2是相同的。

3肯定会慢一些。

说了这么多,这样做仅仅300次,第二次,你不会注意到任何区别。你知道到底有多少计算机可以用原始的CPU +内存的第二个方面做的?一般情况下,你应该写$ C $下的透明度的作为最重要的事情。通过一切手段担心性能 - 但只有当你有一个方法来衡量它,以便一)告诉你是否的需要的担心,以及b)是否有任何的改变确实提高了性能

在这种情况下,我会说,选项1是最清楚的,所以这就是我想要的使用。

I am using C# (This question is also valid for similar languages like C++) and I am trying to figure out the fastest and most efficient way to increment. It isn't just one or two increments, in my game, its like 300 increments per second. Like the Frames of every sprite on the screen are incrementing, the speed and positions of my rpg character, the offset of the camera etc. So I am thinking, what way is the most efficient? e.g for incrementing 5 y_pos on every movement I can do:

1.

Player.YPos += 5;

2.

Player.YPos = Player.YPos + 5;

3.

for (int i = 0; i < 5; i++)
{
    Player.YPos++;
}

Which is the most efficient (and fastest)?

解决方案

(Answer specific to C# as C++ may vary significantly.)

1 and 2 are equivalent.

3 would definitely be slower.

Having said that, doing this a mere 300 times a second, you wouldn't notice any difference. Are you aware of just how much a computer can do in terms of raw CPU+memory in a second? In general, you should write code for clarity as the most important thing. By all means worry about performance - but only when you have a way to measure it, in order to a) tell whether you need to worry, and b) whether any changes actually improve the performance.

In this case, I'd say that option 1 is the clearest, so that's what I'd use.

这篇关于这是更快? ++ + =或x + 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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