Is there a faster 'inline' possiblity for Class functions?

M

MrThingy

How can I have a function within a class that I know is going to be
called almost thousands of times during a loop cycle and have it run as
fast as possible, without using bug-prone #define macros?

I've read some information that says that ordinary Class member
functions running on private data tend to be optimised by the compiler
anyway?

-------------

Long boring bit: I'm currently converting an old program which has a
global array of the form:-

int *heightMap; // standard heightfield for landscape

which is allocated size:-

heightMap = new int[width * height]; // where "width" and "height" are
stated using #defines.

I used to access this array using a cheap and nasty #define function.

#define indexMap(x, y) ((x)&(width-1) + ((y)&(height-1)) * width) // yuck!

I'm now rewriting the code using sensible and easy to read classes, but
I'd like to be able to call something like:

current_height = Landscape.indexMap(x, y);

int Landscape::indexMap(int x, int y) {
return ((x)&(width-1) + ((y)&(height-1)) * width)
}

lots of times during the main program loop.
 
K

Karl Heinz Buchegger

MrThingy said:
How can I have a function within a class that I know is going to be
called almost thousands of times during a loop cycle and have it run as
fast as possible, without using bug-prone #define macros?

Exactly as you did it: Create an inline function.
Your function is simple enough that most compilers will optimize
it by inlining the code directly at the callers side.

class Landscape
{
public:
....

int indexMap(int x, int y) {
return ((x)&(width-1) + ((y)&(height-1)) * width)
}
....
};
 
S

Samee Zahur

I've read some information that says that ordinary Class member
functions running on private data tend to be optimised by the compiler
anyway?
Exactly, and in a function as simple as this, you shouldn't have to
worry about inlining it yourself.

And since you are converting from #defines to consts anyway, you
might as well consider declaring width and height as consts as well -
they let you tuck constants inside namespaces/class scopes. Avoids
naming conflicts.

Samee
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top