<p>Is there a performance difference between <code>i++</code> and <code>++i</code> if the resulting value is not used?</p>

[{'answer_id': 24887, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 10, 'selected': True, 'text': "<p>Executive summary:  No.</p>\n\n<p><code>i++</code> could potentially be slower than <code>++i</code>, since the old value of <code>i</code>\nmight need to be saved for later use, but in practice all modern\ncompilers will optimize this away.</p>\n\n<p>We can demonstrate this by looking at the code for this function,\nboth with <code>++i</code> and <code>i++</code>.</p>\n\n<pre><code>$ cat i++.c\nextern void g(int i);\nvoid f()\n{\n    int i;\n\n    for (i = 0; i &lt; 100; i++)\n        g(i);\n\n}\n</code></pre>\n\n<p>The files are the same, except for <code>++i</code> and <code>i++</code>:</p>\n\n<pre><code>$ diff i++.c ++i.c\n6c6\n&lt;     for (i = 0; i &lt; 100; i++)\n---\n&gt;     for (i = 0; i &lt; 100; ++i)\n</code></pre>\n\n<p>We'll compile them, and also get the generated assembler:</p>\n\n<pre><code>$ gcc -c i++.c ++i.c\n$ gcc -S i++.c ++i.c\n</code></pre>\n\n<p>And we can see that both the generated object and assembler files are the same.</p>\n\n<pre><code>$ md5 i++.s ++i.s\nMD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e\nMD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e\n\n$ md5 *.o\nMD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22\nMD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22\n</code></pre>\n"}, {'answer_id': 25077, 'author': 'Jason Z', 'author_id': 2470, 'author_profile': 'https://Stackoverflow.com/users/2470', 'pm_score': 0, 'selected': False, 'text': '<p>My C is a little rusty, so I apologize in advance.  Speedwise, I can understand the results.  But, I am confused as to how both files came out to the same MD5 hash.  Maybe a for loop runs the same, but wouldn\'t the following 2 lines of code generate different assembly?</p>\n\n<pre><code>myArray[i++] = "hello";\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>myArray[++i] = "hello";\n</code></pre>\n\n<p>The first one writes the value to the array, then increments i.  The second increments i then writes to the array.  I\'m no assembly expert, but I just don\'t see how the same executable would be generated by these 2 different lines of code.</p>\n\n<p>Just my two cents.</p>\n'}, {'answer_id': 25081, 'author': 'Kristopher Johnson', 'author_id': 1175, 'author_profile': 'https://Stackoverflow.com/users/1175', 'pm_score': 3, 'selected': False, 'text': "<p>In C, the compiler can generally optimize them to be the same if the result is unused.</p>\n\n<p>However, in C++ if using other types that provide their own ++ operators, the prefix version is likely to be faster than the postfix version.  So, if you don't need the postfix semantics, it is better to use the prefix operator.</p>\n"}, {'answer_id': 25657, 'author': 'JProgrammer', 'author_id': 1675, 'author_profile': 'https://Stackoverflow.com/users/1675', 'pm_score': 4, 'selected': False, 'text': '<p>Taking a leaf from Scott Meyers, <a href="https://rads.stackoverflow.com/amzn/click/com/020163371X" rel="noreferrer" rel="nofollow noreferrer">More Effective c++</a> <em>Item 6: Distinguish between prefix and postfix forms of increment and decrement operations</em>.</p>\n\n<p>The prefix version is always preferred over the postfix in regards to objects, especially in regards to iterators.</p>\n\n<p>The reason for this if you look at the call pattern of the operators.</p>\n\n<pre><code>// Prefix\nInteger&amp; Integer::operator++()\n{\n    *this += 1;\n    return *this;\n}\n\n// Postfix\nconst Integer Integer::operator++(int)\n{\n    Integer oldValue = *this;\n    ++(*this);\n    return oldValue;\n}\n</code></pre>\n\n<p>Looking at this example it is easy to see how the prefix operator will always be more efficient than the postfix. Because of the need for a temporary object in the use of the postfix.</p>\n\n<p>This is why when you see examples using iterators they always use the prefix version.</p>\n\n<p>But as you point out for int\'s there is effectively no difference because of compiler optimisation that can take place.</p>\n'}, {'answer_id': 25668, 'author': 'Andrew Grant', 'author_id': 1043, 'author_profile': 'https://Stackoverflow.com/users/1043', 'pm_score': 6, 'selected': False, 'text': "<p>A better answer is that <code>++i</code> will sometimes be faster but never slower.</p>\n<p>Everyone seems to be assuming that <code>i</code> is a regular built-in type such as <code>int</code>. In this case there will be no measurable difference.</p>\n<p>However if <code>i</code> is  complex type then you may well find a measurable difference. For <code>i++</code> you must make a copy of your class before incrementing it. Depending on what's involved in a copy it could indeed be slower since with <code>++i</code> you can just return the final value.</p>\n<pre><code>Foo Foo::operator++()\n{\n  Foo oldFoo = *this; // copy existing value - could be slow\n  // yadda yadda, do increment\n  return oldFoo;\n}\n</code></pre>\n<p>Another difference is that with <code>++i</code> you have the option of returning a reference instead of a value. Again, depending on what's involved in making a copy of your object this could be slower.</p>\n<p>A real-world example of where this can occur would be the use of iterators. Copying an iterator is unlikely to be a bottle-neck in your application, but it's still good practice to get into the habit of using <code>++i</code> instead of <code>i++</code> where the outcome is not affected.</p>\n"}, {'answer_id': 39286, 'author': 'tonylo', 'author_id': 4071, 'author_profile': 'https://Stackoverflow.com/users/4071', 'pm_score': 4, 'selected': False, 'text': "<p>Here's an additional observation if you're worried about micro optimisation. Decrementing loops can 'possibly' be more efficient than incrementing loops (depending on instruction set architecture e.g. ARM), given:</p>\n\n<pre><code>for (i = 0; i &lt; 100; i++)\n</code></pre>\n\n<p>On each loop you you will have one instruction each for:</p>\n\n<ol>\n<li>Adding <code>1</code> to <code>i</code>.  </li>\n<li>Compare whether <code>i</code> is less than a <code>100</code>.</li>\n<li>A conditional branch if <code>i</code> is less than a <code>100</code>.</li>\n</ol>\n\n<p>Whereas a decrementing loop:</p>\n\n<pre><code>for (i = 100; i != 0; i--)\n</code></pre>\n\n<p>The loop will have an instruction for each of:</p>\n\n<ol>\n<li>Decrement <code>i</code>, setting the CPU register status flag.</li>\n<li>A conditional branch depending on CPU register status (<code>Z==0</code>).</li>\n</ol>\n\n<p>Of course this works only when decrementing to zero!</p>\n\n<p>Remembered from the ARM System Developer's Guide.</p>\n"}, {'answer_id': 39306, 'author': 'Sébastien RoccaSerra', 'author_id': 2797, 'author_profile': 'https://Stackoverflow.com/users/2797', 'pm_score': 7, 'selected': False, 'text': '<p>From <a href="http://www.drdobbs.com/architecture-and-design/efficiency-versus-intent/228700184" rel="noreferrer">Efficiency versus intent</a> by Andrew Koenig :</p>\n\n<blockquote>\n  <p>First, it is far from obvious that <code>++i</code> is more efficient than <code>i++</code>, at least where integer variables are concerned.</p>\n</blockquote>\n\n<p>And :</p>\n\n<blockquote>\n  <p>So the question one should be asking is not which of these two operations is faster, it is which of these two operations expresses more accurately what you are trying to accomplish.  I submit that if you are not using the value of the expression, there is never a reason to use <code>i++</code> instead of <code>++i</code>, because there is never a reason to copy the value of a variable, increment the variable, and then throw the copy away.</p>\n</blockquote>\n\n<p>So, if the resulting value is not used, I would use <code>++i</code>. But not because it is more efficient: because it correctly states my intent. </p>\n'}, {'answer_id': 107193, 'author': 'Andy Lester', 'author_id': 8454, 'author_profile': 'https://Stackoverflow.com/users/8454', 'pm_score': 3, 'selected': False, 'text': '<p>Please don\'t let the question of "which one is faster" be the deciding factor of which to use.  Chances are you\'re never going to care that much, and besides, programmer reading time is far more expensive than machine time.</p>\n\n<p>Use whichever makes most sense to the human reading the code.</p>\n'}, {'answer_id': 208164, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I always prefer pre-increment, however ...</p>\n\n<p>I wanted to point out that even in the case of calling the operator++ function, the compiler will be able to optimize away the temporary if the function gets inlined.  Since the operator++ is usually short and often implemented in the header, it is likely to get inlined.</p>\n\n<p>So, for practical purposes, there likely isn\'t much of a difference between the performance of the two forms.  However, I always prefer pre-increment since it seems better to directly express what I"m trying to say, rather than relying on the optimizer to figure it out.</p>\n\n<p>Also, giving the optmizer less to do likely means the compiler runs faster.</p>\n'}, {'answer_id': 528667, 'author': 'Andreas', 'author_id': 54710, 'author_profile': 'https://Stackoverflow.com/users/54710', 'pm_score': 3, 'selected': False, 'text': "<p>@Mark\nEven though the compiler is allowed to optimize away the (stack based) temporary copy of the variable and gcc (in recent versions) is doing so,\ndoesn't mean <strong>all</strong> compilers will always do so.</p>\n\n<p>I just tested it with the compilers we use in our current project and 3 out of 4 do not optimize it.</p>\n\n<p>Never assume the compiler gets it right, especially if the possibly faster, but never slower code is as easy to read.</p>\n\n<p>If you don't have a really stupid implementation of one of the operators in your code:</p>\n\n<p><strong>Alwas prefer ++i over i++.</strong></p>\n"}, {'answer_id': 24044354, 'author': 'Shahbaz', 'author_id': 912144, 'author_profile': 'https://Stackoverflow.com/users/912144', 'pm_score': 2, 'selected': False, 'text': "<p>I can think of a situation where postfix is slower than prefix increment:</p>\n\n<p>Imagine a processor with register <code>A</code> is used as accumulator and it's the only register used in many instructions (some small microcontrollers are actually like this).</p>\n\n<p>Now imagine the following program and their translation into a hypothetical assembly:</p>\n\n<p>Prefix increment:</p>\n\n<pre><code>a = ++b + c;\n\n; increment b\nLD    A, [&amp;b]\nINC   A\nST    A, [&amp;b]\n\n; add with c\nADD   A, [&amp;c]\n\n; store in a\nST    A, [&amp;a]\n</code></pre>\n\n<p>Postfix increment:</p>\n\n<pre><code>a = b++ + c;\n\n; load b\nLD    A, [&amp;b]\n\n; add with c\nADD   A, [&amp;c]\n\n; store in a\nST    A, [&amp;a]\n\n; increment b\nLD    A, [&amp;b]\nINC   A\nST    A, [&amp;b]\n</code></pre>\n\n<p>Note how the value of <code>b</code> was forced to be reloaded. With prefix increment, the compiler can just increment the value and go ahead with using it, possibly avoid reloading it since the desired value is already in the register after the increment. However, with postfix increment, the compiler has to deal with two values, one the old and one the incremented value which as I show above results in one more memory access.</p>\n\n<p>Of course, if the value of the increment is not used, such as a single <code>i++;</code> statement, the compiler can (and does) simply generate an increment instruction regardless of postfix or prefix usage.</p>\n\n<hr>\n\n<p>As a side note, I'd like to mention that an expression in which there is a <code>b++</code> cannot simply be converted to one with <code>++b</code> without any additional effort (for example by adding a <code>- 1</code>). So comparing the two if they are part of some expression is not really valid. Often, where you use <code>b++</code> inside an expression you cannot use <code>++b</code>, so even if <code>++b</code> were potentially more efficient, it would simply be wrong. Exception is of course if the expression is begging for it (for example <code>a = b++ + 1;</code> which can be changed to <code>a = ++b;</code>).</p>\n"}, {'answer_id': 24045013, 'author': 'cmaster - reinstate monica', 'author_id': 2445184, 'author_profile': 'https://Stackoverflow.com/users/2445184', 'pm_score': 4, 'selected': False, 'text': '<p>First of all: The difference between <code>i++</code> and <code>++i</code> is neglegible in C.</p>\n<hr />\n<p>To the details.</p>\n<h3>1. The well known C++ issue: <code>++i</code> is faster</h3>\n<p>In C++, <code>++i</code> is more efficient iff <code>i</code> is some kind of an object with an overloaded increment operator.</p>\n<p>Why?<br />\nIn <code>++i</code>, the object is first incremented, and can subsequently passed as a const reference to any other function. This is not possible if the expression is <code>foo(i++)</code> because now the increment needs to be done before <code>foo()</code> is called, but the old value needs to be passed to <code>foo()</code>. Consequently, the compiler is forced to make a copy of <code>i</code> before it executes the increment operator on the original. The additional constructor/destructor calls are the bad part.</p>\n<p>As noted above, this does not apply to fundamental types.</p>\n<h3>2. The little known fact: <code>i++</code> <em>may</em> be faster</h3>\n<p>If no constructor/destructor needs to be called, which is always the case in C, <code>++i</code> and <code>i++</code> should be equally fast, right? No. They are virtually equally fast, but there may be small differences, which most other answerers got the wrong way around.</p>\n<p>How can <code>i++</code> be faster?<br />\nThe point is data dependencies. If the value needs to be loaded from memory, two subsequent operations need to be done with it, incrementing it, and using it. With <code>++i</code>, the incrementation needs to be done <em>before</em> the value can be used. With <code>i++</code>, the use does not depend on the increment, and the CPU may perform the use operation <em>in parallel</em> to the increment operation. The difference is at most one CPU cycle, so it is really neglegible, but it is there. And it is the other way round then many would expect.</p>\n'}, {'answer_id': 26482954, 'author': 'Lundin', 'author_id': 584518, 'author_profile': 'https://Stackoverflow.com/users/584518', 'pm_score': 4, 'selected': False, 'text': "<p><em>Short answer:</em></p>\n<p>There is never any difference between <code>i++</code> and <code>++i</code> in terms of speed. A good compiler should not generate different code in the two cases.</p>\n<p><em>Long answer:</em></p>\n<p>What every other answer fails to mention is that the difference between <code>++i</code> versus <code>i++</code> only makes sense within the expression it is found.</p>\n<p>In the case of <code>for(i=0; i&lt;n; i++)</code>, the <code>i++</code> is alone in its own expression: there is a sequence point before the <code>i++</code> and there is one after it. Thus the only machine code generated is &quot;increase <code>i</code> by <code>1</code>&quot; and it is well-defined how this is sequenced in relation to the rest of the program. So if you would change it to prefix <code>++</code>, it wouldn't matter in the slightest, you would still just get the machine code &quot;increase <code>i</code> by <code>1</code>&quot;.</p>\n<p>The differences between <code>++i</code> and <code>i++</code> only matters in expressions such as <code>array[i++] = x;</code> versus <code>array[++i] = x;</code>. Some may argue and say that the postfix will be slower in such operations because the register where <code>i</code> resides has to be reloaded later. But then note that the compiler is free to order your instructions in any way it pleases, as long as it doesn't &quot;break the behavior of the abstract machine&quot; as the C standard calls it.</p>\n<p>So while you may assume that <code>array[i++] = x;</code> gets translated to machine code as:</p>\n<ul>\n<li>Store value of <code>i</code> in register A.</li>\n<li>Store address of array in register B.</li>\n<li>Add A and B, store results in A.</li>\n<li>At this new address represented by A, store the value of x.</li>\n<li>Store value of <code>i</code> in register A   // inefficient because extra instruction here, we already did this once.</li>\n<li>Increment register A.</li>\n<li>Store register A in <code>i</code>.</li>\n</ul>\n<p>the compiler might as well produce the code more efficiently, such as:</p>\n<ul>\n<li>Store value of <code>i</code> in register A.</li>\n<li>Store address of array in register B.</li>\n<li>Add A and B, store results in B.</li>\n<li>Increment register A.</li>\n<li>Store register A in <code>i</code>.</li>\n<li>... // rest of the code.</li>\n</ul>\n<p>Just because you as a C programmer is trained to think that the postfix <code>++</code> happens at the end, the machine code doesn't have to be ordered in that way.</p>\n<p>So there is no difference between prefix and postfix <code>++</code> in C. Now what you as a C programmer should be vary of, is people who inconsistently use prefix in some cases and postfix in other cases, without any rationale why. This suggests that they are uncertain about how C works or that they have incorrect knowledge of the language. This is always a bad sign, it does in turn suggest that they are making other questionable decisions in their program, based on superstition or &quot;religious dogmas&quot;.</p>\n<p>&quot;Prefix <code>++</code> is always faster&quot; is indeed one such false dogma that is common among would-be C programmers.</p>\n"}, {'answer_id': 57517045, 'author': 'daShier', 'author_id': 11517179, 'author_profile': 'https://Stackoverflow.com/users/11517179', 'pm_score': 3, 'selected': False, 'text': '<p>I have been reading through most of the answers here and many of the comments, and I didn\'t see any reference to the <strong>one</strong> instance that I could think of where <code>i++</code> is more efficient than <code>++i</code> (and perhaps surprisingly <code>--i</code> <em>was</em> more efficient than <code>i--</code>). That is for C compilers for the DEC PDP-11!</p>\n\n<p>The PDP-11 had assembly instructions for pre-decrement of a register and post-increment, but not the other way around. The instructions allowed any "general-purpose" register to be used as a stack pointer. So if you used something like <code>*(i++)</code> it could be compiled into a single assembly instruction, while <code>*(++i)</code> could not.</p>\n\n<p>This is obviously a very esoteric example, but it does provide the exception where post-increment is more efficient(or I should say <em>was</em>, since there isn\'t much demand for PDP-11 C code these days). </p>\n'}]
['https://Stackoverflow.com/questions/24886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/116/']