Developers Notebook-Tricks

From WxWiki

Jump to: navigation, search

Contents

[edit] Tricks of the Trade

[edit] Swapping Values Without A Temporary Value

[edit] Original

inline void wxSwap (size_t& x, size_t& y)
{
    size_t z = x;
           x = y;
           y = z;
}


[edit] Faster, Modified

inline void wxSwap (size_t& x, size_t& y)
{
    x = x ^ y;
    y = x ^ y;
    x = x ^ y;
}

Use to swap pointers too - wxSwap ((size_t&) pStuff1, (size_t&) pStuff2);


[edit] Template Version

template <class T>
inline void wxSwap (T& x, Tt& y)
{
    x = x ^ y;
    y = x ^ y;
    x = x ^ y;
}

Don't put into #define statements, this'll mess it up.

From Bob of Allegro Fame

[edit] Inlining

Inlining, in general, takes away the cost of the cpu calling a function at the cost of more executable space.

For example, this function in C -

void f (int& i)
{
    i += 1;
}

In Pentium assembly it would look something like (quick sketch, OK :))-

push [i]
call [f] 

proc f
;Whatever increments i += 1
end proc

The point is that inlining removes the call instruction and just pastes whatever was in that proc where the call was, and sometimes gets rid of the push commands (parameter passing).

This saves around 4 or 5 clock cycles on a pentium, but increases the size of the code if called more than once by the size of the function each time over one.

So, from this we have our rules -

[edit] Rules of inlining

  • Whenever you call a function only once (compilers should do this)
  • On "small" functions

[edit] Cyclic Redundancy Check

Moved to CRC

[edit] Faster String Functions

Personal tools