r/learnprogramming • • 1d ago

How do you all improve code.

While solving a CodeForce problem, I know this problem is very basic and easy, I was just getting started.

But while solving I thought about this. How could I improve my code and make it more efficient and fast.
If you want to improve a code and make it more efficient and fast what you exactly think to change and why that change will affect the performance.
I know it does depends upon the problem itself(Like that's why there are more version of a program rather than just V1; V2, V3... is improved in terms of performance, etc. so I know it does takes time), but still.. for a small problem like this one. How could you think to improve it?

This problem there are many ways to solve it, look at this

#include <stdio.h>

int main() {

    int n;
    scanf("%d", &n);

    switch (n % 2) {
        case 0:
            printf("YES");
            // Instead of using break, I used this return.
            // Cause I thought if I use break the program,
            // the program will leave this switch statement,
            // then go down and check if any statement to execute.
            // But, here, It has none so if I just use return 0,
            // I could improve it's performace(I don't know it does helps or not)
            return 0; 
        
        default:
            printf("NO");
            return 0;
    }
    return 0;
}

I know the last statement won't get executed but still if in real life if everyone uses this approach (if there is no code below), won't it be a little faster. Like not only use this but these kind of approaches.

Like in python I would do something like this.

print("YES" if int(input()) % 2 == 0 else "NO")

If I used a standard or like normal approach in this way. I think it's slower. Cause it needs to create memory for n and also free it up. But in above it does not need to allocate or free memory for any number(I think), unlike this below one. Like think my program has more code to execute but it does not need the value of n(this input) and in the below it won't free memory of n after the code but the above one it will(it won't even store it)

n = int(input())

if n % 2 == 0:
    print("YES")
else:    
    print("NO")

Like is there still any way to improve it. I just want to solve it, not validate the inputs, etc.

1 Upvotes

14 comments sorted by

7

u/Substitute_Hecate 1d ago

One thing that'll warp your brain a bit is realizing the compiler is smarter than you. It'll optimize away that extra variable in the C version too, so you're effectively debating syntax sugar at that level. The real difference is negligible until you're looping it millions of times.

For Python, your one-liner avoids the name binding but honestly the garbage collector doesn't work in real-time like you're imagining. The memory gets reclaimed almost instantly either way because the reference count drops to zero.

If you really want to shave nanoseconds on this specific problem, you could read the input as bytes and check the last bit of the last character before the newline. But at that point you're writing unreadable code for an 800-rated problem, which is a terrible habit to build early on.

The habit you should build instead is profiling before you optimize. Guessing what's slow is a trap that leads to wasted time and ugly code. Write it clean first, then measure.

1

u/Scary-Combination-67 1d ago

Ahhh... Man I didn't really knew about reference count and thought that it holds the variable until manually done or the program ends... Will first write clean code!

Thank you brooo!

5

u/lurgi 1d ago

The vast majority of code would be improved by being clearly written and designed. Most code does not need to be as fast as possible, it just needs to be fast enough.

For the code you wrote here, performance is almost meaningless. Sure, I could suggest you writing puts instead of printf and (maybe) fgets and strtol, but anything you do is going make a barely measurable difference. Writing the whole thing in assembly language would get you something faster, but again, barely measurable.

In general, you don't make code faster by making micro-optimizations. Sometimes you can find something in a hotspot that can be tweaked, but mostly you use a better algorithm or data structure and see your wins that way. Sometimes you can rearrange things in data to take advantage of CPU cache lines, but this is quite an art and I would never consider doing this unless every other option had been eliminated.

1

u/Scary-Combination-67 1d ago

I'm new to c and didn't knew about fgets or strtol . But I got it, these  micro-optimizations might not even matter in real life and just make my code ugly. But, still I'll try to optimize my code much better and clean way. Thank you broo!

1

u/lurgi 1d ago

You have already done the only optimization that matters, by determining that a simple evenness test is all you need.

However, your code has a bug. There is one input for which it gives the wrong answer.

1

u/Scary-Combination-67 1d ago

Huhhh... Which...

1

u/DrShocker 21h ago

I'll give you a hint: it's one of the even numbers

(although I'm not personally sure it's wrong as the question is phrased)

1

u/lurgi 17h ago

True. The problem is ambiguously worded. Is it valid for one of the boys to get nothing?

3

u/SharkSymphony 1d ago edited 19h ago

To measure performance, you'll want to run this code a bunch of times and measure the timing vs a baseline. Which might be easier if you refactored it into a helper function your main function will call.

I would not expect your approach to improve performance much if at all. This is going to be super fast regardless of whether you use break or return. 💨

2

u/Scary-Combination-67 1d ago

Thanks bro... I guess my imagination about compilers and interpreter was a bit misleading and I'll focus to write code first and then optimize it

3

u/Primary_Olive_5444 1d ago

Rather than improving code, first figure out how much headroom is left on the current hardware / cpu cores that is not utilised yet / L3 and L2 size and hit rate

2

u/Scary-Combination-67 1d ago

Lowkey don't know much about how CPU works. But hope I'll get soon. Anyways, Thank you brooo

1

u/Sufficient-Tale6131 16h ago

Others already covered the performance side (the compiler makes the break and return versions basically identical, and in Python the one-liner vs a named variable is noise). On the bug lurgi mentioned, since you asked: try n = 2. It's even, so your code prints YES, but the problem needs both parts to be even and positive, and 2 can only be split into 1 + 1. So the condition is "n is even and n > 2", e.g. n % 2 == 0 && n > 2 in C.

That's the more useful takeaway for competitive programming: before thinking about speed, test the smallest and boundary inputs from the constraints (here n is 1 to 100, so try 1, 2, 3, 4 and 100). Most wrong answers on easy problems come from edge cases like this, not from code being too slow. If you want to know whether a change actually matters for speed, time it on a large input or compare the generated assembly in Compiler Explorer; for a problem this size both versions finish in well under a millisecond.

1

u/jacksonanna373 2h ago

In C, `int n` is an automatic local; you don't manually free it. `free` is for dynamically allocated memory, and this local's storage ends when `main` returns.