Coding tips & tricks

I'm writing this here as it can eventually help some amateur devs like me, because these are tips you can't know if you haven't read it somewhere by luck, or learned it at school, and also of course as a convenient memo for myself too ;-)



   C/C++


*
Faster incrementation: ++var; instead of var++;
Post-increment usually involves keeping a copy of the previous value, which can be usefull in some (very rare) cases, but most of the time pre-incrementation will save a little bit of memory and exec time (more instructions in underlaying asm)

* Faster multiple declarations/initialisations:
   int var1(val1), var2 (val2);
instead of
   int var1=val1, var2=val2;
Same reasons as above, syntax particularity

* Declare a string (char tab) quickly in C
   char *myString = "This is not a string.";

* Get the size of a file in bytes with sys/stat (under windows)
   (#include <sys/stat.h>)
   struct _stat statBuffer;
   _stat("filename", &statBuffer); // equals 0 if succeeds
   int fileSize = (int)statBuffer.st_size;

* Function pointers syntax
   // declaration and initialisation
   type (*my_f_ptr)(arg0_type, arg1_type) = my_f_name;
   // call
   my_f_ptr(arg0, arg1);

* The maximum size of an signed int is 2147483647 and the minimum is -2147483648.

* unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements. (great for entity system implementations!)


   ASM (80x86)


*
Faster JMP in Turbo-Assembler: JMP SHORT label instead of JMP label
To use if you are certain that the label is less than 128 bytes ahead or 127 bytes back from the jmp instruction. If you don't do it, TASM (because it's a one-pass assembler) will eventually make sure there is enough space for a long jump in your place by inserting a NOP instruction after it. Note that this doesn't change anything to conditional jumps like JGE, as these are always short.

* Make conditional jumps to far away (more than 128B) locations:
   CMP AX, 0CAFEh
   JNE @@Bypass0
   JMP FarAwayLabel0
   @@Bypass0:
   ; code that is more than 127 bytes
   FarAwayLabel0:
   ; to do if the condition is true

instead of
   CMP AX, 0CAFEh
   JE FarAwayLabel0
   ; code that is more than 127 bytes (too long, won't work)
   FarAwayLabel0:
   ; to do if the condition is true


   JavaScript


* Get nearest lower integer from given float f, equivalent of Math.floor():
   var x = ~~f;