473,837 Members | 1,476 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Does Virtual Function Impact on the efficiency of program

For OO design, I like using virtual member function.But considering
efficiency, template is better. Look at this program,

class Animal
{
public:
virtual void Walk() = 0;
};

class Dog
{
public:
virtual void Walk()
{
// ...
}
};

Virtual member function will make our object adding a virtual table
pointer( size: 4 ).When using Virtual member function, computer must
read the pointer value, and then find the virtual table.

// use template
template <SonClassType >
class Animal
{
public:
void Walk()
{
return static_cast<Son ClassType*>(thi s)->WalkMe();
}
};

class Dog : public Animal <Dog>
{
public:
void WalkMe()
{
// ....
}
};

Using template , you call the Walk(), and then WalkMe() is called, So
It is also two times. Some books say virtual function will Impact on
the efficiency of program, so I cannot understand( In this program,
they both 2 times ). In this program, which is the better one
( efficiency )?
Nov 21 '08 #1
5 2961
want.to.be.prof esser wrote:
( In this program,
they both 2 times ). In this program, which is the better one
( efficiency )?
The one that is shorter and clearer (which, for most people I guess,
would be the first one.) As for any micro-optimizations, care about that
after profiling. JFTR, I don't think your "template" version will be any
faster since it's also doing an indirect function call but that should
be a totally uninteresting detail.
Nov 21 '08 #2
want.to.be.prof esser wrote:
For OO design, I like using virtual member function.But considering
efficiency, template is better.
Calling a virtual function is slightly slower than calling a regular
function, but not much. In most cases the difference is negligible
(especially if the function in question performs lots of operations).

The only situation where virtual vs. non-virtual may result in a
considerable difference is if you need to call the function a huge
amount of times in a tight loop, and the implementation if the function
is itself also very short and fast. In this case overhead of the virtual
indirection can become significant. However, it's usually rare to even
need virtual function in such situations.
Nov 21 '08 #3
want.to.be.prof esser wrote:
For OO design, I like using virtual member function.But considering
efficiency, template is better. Look at this program,

class Animal
{
public:
virtual void Walk() = 0;
};

class Dog
{
public:
virtual void Walk()
{
// ...
}
};

Virtual member function will make our object adding a virtual table
pointer( size: 4 ).When using Virtual member function, computer must
read the pointer value, and then find the virtual table.

// use template
template <SonClassType >
class Animal
{
public:
void Walk()
{
return static_cast<Son ClassType*>(thi s)->WalkMe();
}
};

class Dog : public Animal <Dog>
{
public:
void WalkMe()
{
// ....
}
};

Using template , you call the Walk(), and then WalkMe() is called,
So It is also two times. Some books say virtual function will
Impact on the efficiency of program, so I cannot understand( In
this program, they both 2 times ). In this program, which is the
better one ( efficiency )?
The template requires that the type is known at compile time. The
virtual function call can be resolved at run time. If you need the
latter, a virtual function is a good choice.

If you don't need it, don't use it. :-)
Bo Persson

Nov 21 '08 #4
On 2008-11-21 15:23, want.to.be.prof esser wrote:
For OO design, I like using virtual member function.But considering
efficiency, template is better. Look at this program,
Virtual member function will make our object adding a virtual table
pointer( size: 4 ).When using Virtual member function, computer must
read the pointer value, and then find the virtual table.
Using template , you call the Walk(), and then WalkMe() is called, So
It is also two times. Some books say virtual function will Impact on
the efficiency of program, so I cannot understand( In this program,
they both 2 times ). In this program, which is the better one
( efficiency )?
Virtual functions and templates serves different purposes, you only need
virtual functions when you do not know the exact type while your are
writing the code (i.e. the type will be determined at run-time), while
templates are used when you do know the exact type at compile-time.

Virtual functions do come with a slight penalty but in most cases it is
negligible. A rule of thumb is to not make functions virtual unless you
have to (i.e. you need to override them in a derived class) but don't be
afraid to do so when you have to.

--
Erik Wikström
Nov 21 '08 #5

"Erik Wikström" <Er***********@ telia.comwrote:
>
Virtual functions do come with a slight penalty but in most cases it is
negligible. A rule of thumb is to not make functions virtual unless you
have to (i.e. you need to override them in a derived class) but don't be
afraid to do so when you have to.
Also all decent C++ compilers including the earliest versions of cfront will
optimize away the overhead of calling a vitrual function when possible, such
as
when you are calling the meber from an actual object rather than a
base-class pointer/reference.

Nov 21 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

30
3530
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then I've also heard there are lots of weird ways to do some things kinda like Perl which is bad for me. Any other ideas?
25
5426
by: Stijn Oude Brunink | last post by:
Hello, I have the following trade off to make: A base class with 2 virtual functions would be realy helpfull for the problem I'm working on. Still though the functions that my program will use a lot are the ones that are virtual and thus will slow down the calculation, at least that is what what I have read on several places on the internet. It makes sense the program has to work with some kind off lookup table for the virtual...
16
1717
by: Michael P. O'Connor | last post by:
it was my understanding that if you were to declare a function as virtual you could not declare a body for it in the class it was declared virtual, but playing around with it tonight, it let me do this. and with the following code class a { public: virtual void fun() {std::cout << "class a" << std::endl; };
41
3836
by: Materialised | last post by:
I am writing a simple function to initialise 3 variables to pesudo random numbers. I have a function which is as follows int randomise( int x, int y, intz) { srand((unsigned)time(NULL)); x = rand(); y = rand();
6
5357
by: Dan | last post by:
Maybe the title is a little misleading, but I don't know a better way of putting it. What I would like to do, is create a file pointer that really isn't pointing to an actual file on disk, but a string in memory. In other words whatever is being written to the file is actually being written to a string instead. Is there any straight forward way of doing this.
58
30266
by: Larry David | last post by:
Ok, first of all, let's get the obvious stuff out of the way. I'm an idiot. So please indulge me for a moment. Consider it an act of "community service".... What does "64bit" mean to your friendly neighborhood C# programmer? The standard answer I get from computer sales people is: "It means that the CPU can process 64 bits of data at a time instead of 32." Ok... I guess I *kind* of understand what that means at an intuitive level, but what...
3
1723
by: Imre | last post by:
Hi! I've got some questions regarding heavy use of virtual inheritance. First, let's see a theoretical situation, where I might feel tempted to use a lot of virtual inheritance. Let's suppose, we're creating a little strategy game. In our game, there are Units. A Unit can be either a Human, or a Vehicle. Obviously, Human and Vehicle are subclasses of Unit.
12
4813
by: lali.b97 | last post by:
Somewhere in a tutorial i read that if statement has performance overheads as code within the if statement cannot take benefit of pipeling of microprocessor and also that the compiler cannot agressively optimize that code. my functions as much as possible and also try to have minimum code withing if block.
8
1842
by: lmfmaw | last post by:
Hi all, I've hit the wall with this "fairly" simple problem. As you can see in the code below, my destructors don't do their job as they are supposed to (I left them empty for this example). I'm running the Visual Leak Detector library (on VS 2005) to detect memory leaks and whatever I've tried it still complains.. Please can someone help me clean up properly? --------
0
9843
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10566
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10623
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9401
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7806
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7001
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5848
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4040
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.