Performant C++ Code

This is a list of benchmarking done while programming in C++.


Unique Pointer for reading file data (ifstream) vs using normal variable

I had a class which when instantiated it will open a .exe file to be able to read its hex values and then it has a function to read the first 2-bytes.

When using a standard std::ifstream variable and then printing the first 2 bytes from the file it takes approx 0.4 – 0.7ms to read and print them.

However, when you have the file stored in a unique_ptr when you instantiate the class and then print the first 2-bytes it takes approx 0.2 – 0.35ms which is a lot faster than using a standard std::ifstream variable.

Conclusion: Use an unique_ptr to access file contents with ifstream as it is quicker.


Initialising Vectors


Initialised std::array vs std::vector

I tested the following:

{
    Timer time3("Vec uninitialised");
    std::vector<int> vec{ 2, 3, 2 };

    for (int i{ 0 }; i < 3; ++i)
    {
        std::cout << vec.at(i);
    }
}



{
    Timer time("std::array");
    std::array<int, 3> arr { 2, 3, 2 };
    for (int i{ 0 }; i < 3; ++i)
    {
        std::cout << arr.at(i);
    }
}

The std::array is ~twice as fast.

In