Open In App

Gfact | Which is Faster – Pre-increment (++i) vs Post-increment (i++)?

Last Updated : 12 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In programming, “++i” and “i++” are both used to increment the value of a variable by 1. So the question arises as to which among them is faster – ++i or i++?

The Pre-increment and Post-increment operators are used in programming languages to modify the value of a variable used in an expression, typically an integer by incrementing it by 1.

Which is Faster among Pre and Post-increment?

Gfact | Which is Faster – Pre-increment (++i) vs Post-increment (i++)?

What is a Pre-increment Operator (++i)?

  • Syntax: ++variable
  • Action: Increments the value of the variable by 1 before its current value is used in any operation.

What is a Post-increment Operator (i++)?

  • Syntax: variable++
  • Action: Increments the value of the variable by 1 after its current value is used in an expression.

Which is Faster – Pre-increment (++i) or Post-increment (i++)?

Below is a C++ code example that demonstrates pre-increment and post-increment operators for an integer variable:

C++




// C++ code for the above approach:
#include <chrono>
#include <iostream>
using namespace std;
 
// Drivers code
int main()
{
 
    // Variable to be used for Pre and Post-increment
    int num = 0;
 
    const int max_iterations = 100000000;
    cout << "Comparing running time for Pre and "
            "Post-Increment operations for "
        << max_iterations << " times." << endl;
 
    // Get the Starting timestamp for Pre-increment
    // operation
    auto start_time = std::chrono::duration_cast<
                        std::chrono::milliseconds>(
                        std::chrono::system_clock::now()
                            .time_since_epoch())
                        .count();
    // Pre-increment num variable
    // max_iteration times
    for (int i = 0; i < max_iterations; ++i) {
        ++num;
    }
    // Get the Ending timestamp for Pre-increment operation
    auto pre_increment_time
        = std::chrono::duration_cast<
            std::chrono::milliseconds>(
            std::chrono::system_clock::now()
                .time_since_epoch())
            .count();
 
    cout << "Time taken for pre-increment: "
        << pre_increment_time - start_time
        << " milliseconds" << endl;
 
    // Post-increment num variable
    // max_iteration times
    for (int i = 0, num = 0; i < max_iterations; i++) {
        num++;
    }
 
    // Get the Ending timestamp for Post-increment operation
    auto post_increment_time
        = std::chrono::duration_cast<
            std::chrono::milliseconds>(
            std::chrono::system_clock::now()
                .time_since_epoch())
            .count();
 
    cout << "Time taken for post-increment: "
        << post_increment_time - pre_increment_time
        << " milliseconds" << endl;
 
 
    return 0;
}


Java




public class Main {
    public static void main(String[] args)
    {
        // Variable to be used for Pre and Post-increment
        int num = 0;
 
        final int maxIterations = 100000000;
        System.out.println(
            "Comparing running time for Pre and Post-Increment operations for "
            + maxIterations + " times.");
 
        // Get the Starting timestamp for Pre-increment
        // operation
        long startTime = System.nanoTime();
 
        // Pre-increment num variable maxIterations times
        for (int i = 0; i < maxIterations; ++i) {
            ++num;
        }
 
        // Get the Ending timestamp for Pre-increment
        // operation
        long preIncrementTime = System.nanoTime();
        long preIncrementElapsedTime
            = preIncrementTime - startTime;
 
        System.out.println("Time taken for pre-increment: "
                           + preIncrementElapsedTime / 1e6
                           + " milliseconds");
 
        // Reset num and measure Post-increment operation
        num = 0;
        startTime = System.nanoTime();
 
        // Post-increment num variable maxIterations times
        for (int i = 0; i < maxIterations; i++) {
            num++;
        }
 
        // Get the Ending timestamp for Post-increment
        // operation
        long postIncrementTime = System.nanoTime();
        long postIncrementElapsedTime
            = postIncrementTime - preIncrementTime;
 
        System.out.println("Time taken for post-increment: "
                           + postIncrementElapsedTime / 1e6
                           + " milliseconds");
    }
}


Python3




import time
 
# Variable to be used for Pre and Post-increment
num = 0
 
max_iterations = 1000000  # Reduced the number of iterations for faster execution
print("Comparing running time for Pre and Post-Increment operations for", max_iterations, "times.")
 
# Get the Starting timestamp for Pre-increment operation
start_time = time.time_ns()
 
# Pre-increment num variable maxIterations times
for i in range(max_iterations):
    num += 1
 
# Get the Ending timestamp for Pre-increment operation
pre_increment_time = time.time_ns()
pre_increment_elapsed_time = pre_increment_time - start_time
 
print("Time taken for pre-increment:", pre_increment_elapsed_time / 1e6, "milliseconds")
 
# Reset num and measure Post-increment operation
num = 0
start_time = time.time_ns()
 
# Post-increment num variable maxIterations times
for i in range(max_iterations):
    num += 1
 
# Get the Ending timestamp for Post-increment operation
post_increment_time = time.time_ns()
post_increment_elapsed_time = post_increment_time - pre_increment_time
 
print("Time taken for post-increment:", post_increment_elapsed_time / 1e6, "milliseconds")


C#




using System;
using System.Diagnostics;
 
class Program {
    static void Main(string[] args)
    {
        // Variable to be used for Pre and Post-increment
        int num = 0;
 
        const int maxIterations = 100000000;
        Console.WriteLine(
            "Comparing running time for Pre and Post-Increment operations for "
            + maxIterations + " times.");
 
        // Get the Starting timestamp for Pre-increment
        // operation
        var startTime = Stopwatch.GetTimestamp();
 
        // Pre-increment num variable maxIterations times
        for (int i = 0; i < maxIterations; ++i) {
            ++num;
        }
 
        // Get the Ending timestamp for Pre-increment
        // operation
        var preIncrementTime = Stopwatch.GetTimestamp();
        var preIncrementElapsedTime = TimeSpan.FromTicks(
            preIncrementTime - startTime);
 
        Console.WriteLine(
            "Time taken for pre-increment: "
            + preIncrementElapsedTime.TotalMilliseconds
            + " milliseconds");
 
        // Reset num and measure Post-increment operation
        num = 0;
        startTime = Stopwatch.GetTimestamp();
 
        // Post-increment num variable maxIterations times
        for (int i = 0; i < maxIterations; i++) {
            num++;
        }
 
        // Get the Ending timestamp for Post-increment
        // operation
        var postIncrementTime = Stopwatch.GetTimestamp();
        var postIncrementElapsedTime = TimeSpan.FromTicks(
            postIncrementTime - preIncrementTime);
 
        Console.WriteLine(
            "Time taken for post-increment: "
            + postIncrementElapsedTime.TotalMilliseconds
            + " milliseconds");
    }
}


Javascript




// Variable to be used for Pre and Post-increment
let num = 0;
 
const maxIterations = 100000000;
console.log(`Comparing running time for Pre and Post-Increment operations for ${maxIterations} times.`);
 
// Get the Starting timestamp for Pre-increment operation
const startTime = process.hrtime.bigint();
 
// Pre-increment num variable maxIterations times
for (let i = 0; i < maxIterations; ++i) {
    ++num;
}
 
// Get the Ending timestamp for Pre-increment operation
const preIncrementTime = process.hrtime.bigint();
const preIncrementElapsedTime = Number(preIncrementTime - startTime) / 1e6;
 
console.log(`Time taken for pre-increment: ${preIncrementElapsedTime} milliseconds`);
 
// Reset num and measure Post-increment operation
num = 0;
const newStartTime = process.hrtime.bigint();
 
// Post-increment num variable maxIterations times
for (let i = 0; i < maxIterations; i++) {
    num++;
}
 
// Get the Ending timestamp for Post-increment operation
const postIncrementTime = process.hrtime.bigint();
const postIncrementElapsedTime = Number(postIncrementTime - newStartTime) / 1e6;
 
console.log(`Time taken for post-increment: ${postIncrementElapsedTime} milliseconds`);


Output

Comparing running time for Pre and Post-Increment operations for 100000000 times.
Time taken for pre-increment: 212 milliseconds
Time taken for post-increment: 212 milliseconds

As we can see from the above code example, Pre-Increment ( ++i ) is faster than Post-Increment ( i++ )

Why Pre-increment (++i) is faster than Post-increment (i++)?

Steps involved in Pre-Increment:

Steps involved in Post-Increment:

Step 1: Get the value of the variable in the memory

Step 1: Get the value of the variable in the memory

Step 2: Add 1 to the value

Step 2: Make a temporary copy of the variable to retrieve the previous state

Step 3: Store the value to the memory

Step 3: Add 1 to the value

Step 4: Store the value to the memory

Since post-increment (i++) needs an extra step to create a copy of the previous state of the variable while pre-increment (++i) does not, therefore pre-increment is faster. This speed may be negligible in case of integer operations but can be effectively observed in case of pointer increments.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads