开源日报 每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。
今日推荐开源项目:《玩蛇 SnakeAI》
今日推荐英文原文:《Stop Using i++ in Your Loops》

今日推荐开源项目:《玩蛇 SnakeAI》传送门:GitHub链接
推荐理由:将人工智能与一些古老游戏结合起来会是什么样呢?这个项目使用 AI 来玩贪吃蛇,并且通过类似现实世界的适者生存交配等方式来选出更好的蛇 AI。虽然这两个东西结合起来看上去让人感觉有些小题大做……不过试着让机器来玩简单的游戏会是个挺有意思的事情,在我们的帮助下它能比小时候的我们更强。
今日推荐英文原文:《Stop Using i++ in Your Loops》作者:Devin Soni
原文链接:https://medium.com/better-programming/stop-using-i-in-your-loops-1f906520d548
推荐理由:看看日常生活中的细节有哪些可以优化的

Stop Using i++ in Your Loops

Why ++i is often better than i++ (pre-increment vs. post-increment)

Introduction

If you’ve written a for-loop before, then you have almost definitely used i++ before to increment your loop variable.

However, have you ever thought about why you choose to do it like that?

Clearly, the end result of i++ is that i is one higher than it was before — which is what we want. But, there are many ways to accomplish this, such as ++i, i++, and even i = i + 1.

In this article, I will cover two methods of adding 1, ++i, and i++, and explain why ++i may be better than i++ in most situations.

Post-Increment (i++)

The i++ method, or post-increment, is the most common way.

In psuedocode, the post-increment operator looks roughly as follows for a variable i:
int j = i;
i = i + 1;
return j;
Since the post-increment operator has to return the original value of i, and not the incremented value i + 1, it has to store the old version of i.

This means that it typically needlessly uses additional memory to store that value, since, in most cases, we do not actually use the old version of i, and it is simply discarded.

Pre-Increment (++i)

The ++i method, or pre-increment, is much less common and is typically used by older programmers in languages such as C and C++.

In psuedocode, the pre-increment operator looks roughly like this for a variable i:
i = i + 1;
return i;
Notably, here, we do not have to save the old value of i — we can simply add to it and return. This aligns much better with the typical use-case in a for-loop, since we rarely need the old value of i in that context.

Caveats

After seeing the difference between post-increment and pre-increment, one might notice that, since the cached value of i is never used in post-increment, the compiler will just optimize that line away, making the two operators equivalent.

This is most likely true for primitive types, such as an integer.

However, for more complex types, such as user-defined types or iterators with the + operation overloaded, the compiler may not be able to safely optimize the caching operation.

So, it seems that in most cases, the pre-increment operator is better than, or equal to, the post-increment operator, as long as you do not need the previous value of whatever you are incrementing.
下载开源日报APP:https://openingsource.org/2579/
加入我们:https://openingsource.org/about/join/
关注我们:https://openingsource.org/about/love/