開源日報 每天推薦一個 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/