Microoptimization in C, which ones exist? Is anyone really helpful?

I understand most micro optimizations, but are they really useful?

Exempli gratia: does it ++iinstead i++, or while(1)or for(;;)does it really increase productivity (both in the area of ​​fingerprints and in the processor cycle)?

So the question is, what micro-optimizations can be done in C? Are they really helpful?

+3
source share
13 answers

You must rely on your compiler to optimize this material. Focus on using appropriate algorithms and writing reliable, readable, and maintainable code.

+21

tclhttpd, -, Tcl, , Apache, -, C, , , , - / *.

-, , . SO , , , - .

, , , , . , . , ++ ++ i.

* : . , , , lighttpd, NginX Apache2.

+5

, -, . .

, [] [/edit] - .

+4

, , -, - . - ++i i++, , , , ( ), . pre-increment/decment , .

, - , , . , . , , , . , - , , , , . , .

- . ; . . . , , ( . ).

+4

, , , - ?

- , 20 , , , 80286/386, .

, - , , , , , , , 80386, 4Mb RAM, , 8Mb !!

, , , .

, Intel 80x86, Borland/Microsoft.

, , , .

+3

, , , , , .

, , , , , (, , restrict), . , , , , , .

, , 99% .

+3

, , , , -.

+2

, , , , , . , . , , , .

C, for (;;) , "i ++" " i", , , .

+1

, .

- SO , - " , ". " ", , . , .

, -, ( ) , - , , , .

+1
x ^= y
y ^= x
x ^= y
0

++ ++ , , , ( i), ( , , , ).

0

, , , , , . , , .

, x, x - , x. , , , . ...

int i;
for (i = 0; i < x; i++)
    doStuff(array[i]);

, -

int i;
for (i = x-1; i != 0; i--)
{
    doStuff(array[i]);
}
doStuff(array[0]);

, , .

MaR . , doStuff() int:

int i = x;
while (i != 0)
{
    --i;
    printf("%d\n",doStuff(array[i]));
}

, , .

. , ( ), , , , .

(x < y), :

  • y x, r1
  • test r1, n z
  • n z

(x!= 0), :

  • test x to set the z flag branch
  • based on z flag value

You can skip the subtraction command for each iteration.

There are architectures where you can have a subtraction command that sets flags based on the result of the subtraction, but I'm sure x86 is not one of them, so most of us do not use compilers that have access to such a machine instruction.

0
source

Source: https://habr.com/ru/post/1729385/


All Articles