Solving my homework for Informatics at University, I always find different ways to solve the same problem. One way is the fastest(execution time) but the longest and more complex. And the other is way easier to realize, falls short in execution time, it's easy to understand and so on.
As an mini-example is that we have have to create a program in C++, which outputs a line of N elements where each element has same adjacent elements different of that in the middle.
Ex.
6 Elements: *_*_*_
7 Elements: *_*_*_*
First solution is the easiest:
#include <iostream>
using namespace std;
int main(void){
int a;
cin >> a;
for (int i=1; i<=a; i++)
{
if (i%2 != 0)
{
cout << "*";
}
else
{
cout << " ";
}
}
return 0;
}
And the second one is a little bit harder to implement but faster to execute(less conditionals checks):
#include <iostream>
using namespace std;
int main(void){
int a;
cin >> a;
if (a%2 == 1)
{
for (int i=1; i<=a; i=i+2)
{
cout << "*";
cout << " ";
}
}
else
{
for (int i=1; i<a; i=i+2)
{
cout << "*";
cout << " ";
}
cout << " ";
}
return 0;
}
My question is what should I focus on? Clean code, easy to implement/deploy and better readability or best algorithm, faster to execute and strong logic, or just try as best as possible to mix all these 2, because there is always a discrepancy between these 2 ways of solving problems?
You should try to write readable, easy to debug code for an ease of understanding.
Whenever you encounter portions of code where it can be heavily optimized in order to get much higher performance (either by modifying the code's architecture or/and by implementing assembly in your code), you can add in a commented section the better performance alternative of it. Even if you choose the better performance alternative, you'll always have the other one which can back up you up, in order to understand it.
Also, stick to better performance alternatives when you can see huge gains by doing it so, not every time.
Keep in mind that these improvements are better to be only implemented in the case of performance bottlenecks or in systems where power efficiency is crucial.