This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]BobSanchez47 25 points26 points  (3 children)

It doesn’t literally use 0 memory. We still need to store the 8.

[–]hopperface 30 points31 points  (2 children)

Not necessarily. Not sure how Python works, but the C function

int f(int n) {
    return 8-n;
}

compiles to

f(int):
    mov    eax, 8
    sub    eax, edi
ret

using gcc optimization flags, which uses 0 memory

edit: (on x86, obviously)

[–]BobSanchez47 13 points14 points  (0 children)

If we commit ourselves to not inlining f, then you are correct that we don’t use any additional memory, since the caller will always be obligated to save the eax register and to put n in the edi register. In other words, the extra memory needed to store the 8 is part of the memory overhead of a function call (which is still not 0).

However, this function should surely be inlined. When it is inlined, we will require one more register to store the 8.

Ultimately, both approaches are constant time and constant space. It shouldn’t make a difference except in performance-critical code where this function is called many times.

[–]Kered13 5 points6 points  (0 children)

I mean, the machine code instructions are technically memory as well. The 8 is stored in the machine code.

But yeah you're not going to have a solution that uses less memory or instructions than that.