473,379 Members | 1,216 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Declaring a Constructor in an Interface?

I am accessing my database through an interface, to allow future
substitution of the physical datastore - hence I would like to declare in my
Interface that my DAL-objects implementing the interface and accessing the
datastore MUST pass in a UserToken in the constructor of the object.

Is this not possible?
Am I forced to add the UserToken as a property on the object instead?

/Ole

Nov 16 '05 #1
20 4210
Unfortunately this is not possible.

You may use an abstract class instead which exposes 1 constructor
taking a UserToken though.

I really wished that this was possible, because interfaces are faster than
abstract classes.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Ole Hanson" <ol********@ole.ole> wrote in message
news:eg**************@TK2MSFTNGP09.phx.gbl...
I am accessing my database through an interface, to allow future
substitution of the physical datastore - hence I would like to declare in my Interface that my DAL-objects implementing the interface and accessing the
datastore MUST pass in a UserToken in the constructor of the object.

Is this not possible?
Am I forced to add the UserToken as a property on the object instead?

/Ole

Nov 16 '05 #2
What leads you to the conclusion that interfaces are faster than ABCs?

Regards

Richard Blewett - DevelopMentor

http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<2V*******************@news4.e.nsc.no>

Unfortunately this is not possible.

You may use an abstract class instead which exposes 1 constructor
taking a UserToken though.

I really wished that this was possible, because interfaces are faster than
abstract classes.

--
Regards,
Dennis JD Myr?n
Oslo Kodebureau
"Ole Hanson" <ol********@ole.ole> wrote in message
news:eg**************@TK2MSFTNGP09.phx.gbl...
I am accessing my database through an interface, to allow future
substitution of the physical datastore - hence I would like to declare in my Interface that my DAL-objects implementing the interface and accessing the
datastore MUST pass in a UserToken in the constructor of the object.

Is this not possible?
Am I forced to add the UserToken as a property on the object instead?

/Ole


---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.760 / Virus Database: 509 - Release Date: 10/09/2004

[microsoft.public.dotnet.languages.csharp]
Nov 16 '05 #3
You need to create 2 class instances
when creating an instance of a class which is derived from an abstract
class.

Creating an instance of an abstract class means performance overhead.
I think that is especially true if the abstract class contains virtual
methods.

Virtual methods always means performance overhead.
According to Microsoft they are two times as expensive as non-virtual
methods.

However, abstract members should be as fast as interface members i believe.

An abstract class containing no virtual methods should be nearly as fast
as an interface, but still slower.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Richard Blewett [DevelopMentor]" <ri******@develop.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
What leads you to the conclusion that interfaces are faster than ABCs?

Regards

Richard Blewett - DevelopMentor

http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<2V*******************@news4.e.nsc.no>
Unfortunately this is not possible.

You may use an abstract class instead which exposes 1 constructor
taking a UserToken though.

I really wished that this was possible, because interfaces are faster than abstract classes.

--
Regards,
Dennis JD Myr?n
Oslo Kodebureau
"Ole Hanson" <ol********@ole.ole> wrote in message
news:eg**************@TK2MSFTNGP09.phx.gbl...
> I am accessing my database through an interface, to allow future
> substitution of the physical datastore - hence I would like to declare in
my
> Interface that my DAL-objects implementing the interface and accessing

the > datastore MUST pass in a UserToken in the constructor of the object.
>
> Is this not possible?
> Am I forced to add the UserToken as a property on the object instead?
>
> /Ole
>
>
>


---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.760 / Virus Database: 509 - Release Date: 10/09/2004

[microsoft.public.dotnet.languages.csharp]

Nov 16 '05 #4
Dennis,

this isn't how it works. The base class state and the derived class state are combined into a single object and teh v-tables are combined with the oerridden methods replacing the base class versions in the v-table. You are absoilutely right that virtua dispatch is (marginally) slower than non-virtual due to an extra level of indirection (a lookup that has to be performed at runtime - by lookup I don't mean a search by name or anything like that).

Interfaces are essentially a definition of a v-table and time implementations are a bunch of overrides. Interface based invocation uses virtual dispatch - there is no extra overhead from an ABC compared with an interface.

Regards

Richard Blewett - DevelopMentor

http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<bP*******************@news4.e.nsc.no>

You need to create 2 class instances
when creating an instance of a class which is derived from an abstract
class.

Creating an instance of an abstract class means performance overhead.
I think that is especially true if the abstract class contains virtual
methods.

Virtual methods always means performance overhead.
According to Microsoft they are two times as expensive as non-virtual
methods.

However, abstract members should be as fast as interface members i believe.

An abstract class containing no virtual methods should be nearly as fast
as an interface, but still slower.

--
Regards,
Dennis JD Myr?n
Oslo Kodebureau
"Richard Blewett [DevelopMentor]" <ri******@develop.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
What leads you to the conclusion that interfaces are faster than ABCs?

Regards

Richard Blewett - DevelopMentor

http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<2V*******************@news4.e.nsc.no>
Unfortunately this is not possible.

You may use an abstract class instead which exposes 1 constructor
taking a UserToken though.

I really wished that this was possible, because interfaces are faster than abstract classes.


Nov 16 '05 #5
Hi,
Unfortunately this is not possible.
<snip>
I really wished that this was possible, because interfaces are faster than
abstract classes.


I was thinking about it a long time ago...
.... and i came to conclusion that it should not be an interface.
An abstract constructor in an abstract class has no sense, too.

AFAIK interface works only after initialization of its inherited class,
never before. So, there is no way to initialize class by its interface.
This dogma of interface should not be changed.

Regards

Marcin
Nov 16 '05 #6
Dennis Myrén wrote:
You need to create 2 class instances when creating an instance
of a class which is derived from an abstract class.
No you don't. You end up defining two types, but you only create one
instance.

Here's an example:

public abstract class ABC
{
public abstract void SayHello();
}

public class ConcreteDerived : ABC
{
public override void SayHello() { Console.WriteLine("Hello!"); }
}

And now to use this:

ABC obj = new ConcreteDerived();
obj.SayHello();

I have created just one instance here. I have defined two classes, but I've
only created one instance. (In fact it's impossible to create an instance of
the base class, ABC, because it's abstract. So I couldn't create an instance
of each even if I wanted to.)

(Note, by the way, that this doesn't actually solve the problem as
originally stated. Abstract Base Classes aren't a solution to this
particular issue because you can't inherit constructor signatures.)

Creating an instance of an abstract class means performance
overhead.
I think that is especially true if the abstract class contains
virtual methods.
You can't create an instance of an abstract class. That's what 'abstract'
means!

Also, the presence of virtual methods has no impact on the overhead of
creating an instance of a class, so your argument is slightly confused here
I'm afraid.

There are overheads to virtual methods, but you've missed an important point
here:
Virtual methods always means performance overhead.
According to Microsoft they are two times as expensive as
non-virtual methods.
Yes, but interfaces are even more expensive.

So if you chose to use interfaces instead of abstract base classes to avoid
the overhead of a virtual function call, you've made a bad choice.
Interface method calls are even more expensive than virtual function calls.

The expensive thing is the polymorphic nature of the call. With either
interfaces or virtual methods, the method that ends up getting called will
depend on what type of object you've got, so the JIT-compiled code can't
just call the relevant function directly or inline it. You pay that cost
with either virtual methods or interfaces. And as it happens, interface
method calls are marginally the more expensive of these two call types
today.

(In Whidbey, the next version of .NET, it all gets a little more complex to
work out how much a method call costs, because they appear to detect when
you're not actually exploiting polymorphism and change the way the code
works. It's similar to a technique called 'monomorphic inlining' that some
JVMs use. This means that the cost of polymorphic function calls changes
over time.)

However, abstract members should be as fast as interface members i
believe.
Abstract members *are* virtual. If you use ILDASM to look at what the
compiler generates, this becomes very clear. For example, here's the
abstract SayHello method as defined in my ABC class above:

..method public hidebysig newslot abstract virtual
instance void SayHello() cil managed
{
} // end of method ABC::SayHello

Notice that it is marked as 'abstract virtual'. In the IL, this is
explicit. With C#, to save you typing, they don't make you type in both -
abstract methods *have* to be virtual. A non-virtual abstract method makes
no sense: 'abstract' effectively means 'must override', and you can only
override virtual methods. So if you were to define a non-virtual abstract
method you would effectively be defining a method that derived classes were
required to override, but which couldn't be overridden!

So because 'abstract' only makes sense for virtual methods, in C# writing
'abstract' always implies 'virtual'.

So abstract methods are exactly as expensive as virtual methods, for the
simple reason that they *are* virtual methods.

An abstract class containing no virtual methods should be nearly as
fast as an interface, but still slower.


An abstract class containing no virtual methods would be a slightly unusual
thing, because it would contain no abstract methods... It is actually
possible to write such a class, you just wouldn't normall do it. It would
in fact be substantially faster to use than call interface methods, because
non-virtual methods (which includes all non-abstract methods) are faster
than either virtual methods or interface method calls. But it wouldn't be a
very useful thing - you don't often want to declare an abstract class with
no abstract methods.

But how would an abstract class containing some abstract methods stack up
against an interface? In the current version of the CLR, interface calls are
known to be slightly more expensive, so you would expect this:

Fastest: direct call to non-abstract, non-virtual, non-interface methods
2nd fastest: call through abstract or virtual method
Slowest: call through interface method

But it's always important to test, so I wrote a little program that sees how
many calls a second I can get through each type. Here are the results:

Direct call: 515 million calls per second
Abstract method: 173 million calls per second
Interface method: 155 million calls per second

That's on my laptop, with a 1.6GHz Pentium M, running v1.1 of the .NET
framework. I've copied the program at the end of this message so you can
try it out.

This seems to confirm that interfaces are (on the current .NET framework)
the slowest of the three options. And for this particular test, a
non-abstract, non-interface call is well over twice as fast.

In any case, not only is this not really relevant to the original discussion
(abstract base classes don't help solve the problem any better than
interfaces) this is a bit of a case of micro-optimization. The difference in
performance between these different types of method calls is very often
going to be irrelevant - if the method does anything non-trivial, then the
cost of the work it does will swamp any difference between invocation costs.
(These distinctions really only matter for very simple methods like
straightforward property accessors. In that case, the main difference is
that with a non-interface and non-virtual call, the JIT compiler can inline
the method.)
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/

using System;

public abstract class ABC
{
public abstract void SayHello();
}

public interface IFoo
{
void SayHello();
}

public class ConcreteDerived : ABC
{
public override void SayHello() { }
}

public class InterfaceImpl : IFoo
{
public void SayHello() { }
}

public class NonVirtual
{
public void SayHello() { }
}
class App
{
static void Main()
{
// Run tests multiple times to avoid any transient
// JIT-related overheads

for (int i = 0; i < 5; ++i)
{
SpeedTestNonVirtual(new NonVirtual());
SpeedTestABC(new ConcreteDerived ());
SpeedTestInterface(new InterfaceImpl ());
}
}
const int CallsBetweenTimeChecks = 100000;
static void SpeedTestNonVirtual(NonVirtual obj)
{
DateTime stopBy = DateTime.Now + TimeSpan.FromSeconds(10);
long count = 0;
while (DateTime.Now < stopBy)
{
// Make lots of calls in between time checks, otherwise
// the time take to check the current time dominates.

for (int i = 0; i < CallsBetweenTimeChecks; ++i)
{
obj.SayHello();
count += 1;
}
}
Console.WriteLine("Non-virtual: {0} million calls per second", ((double)
count) / 10000000.0);
}

static void SpeedTestABC(ABC obj)
{
DateTime stopBy = DateTime.Now + TimeSpan.FromSeconds(10);
long count = 0;
while (DateTime.Now < stopBy)
{
// Make lots of calls in between time checks, otherwise
// the time take to check the current time dominates.

for (int i = 0; i < CallsBetweenTimeChecks; ++i)
{
obj.SayHello();
count += 1;
}
}
Console.WriteLine("ABC: {0} million calls per second", ((double) count)
/ 10000000.0);
}

static void SpeedTestInterface(IFoo obj)
{
DateTime stopBy = DateTime.Now + TimeSpan.FromSeconds(10);
long count = 0;
while (DateTime.Now < stopBy)
{
// Make lots of calls in between time checks, otherwise
// the time take to check the current time dominates.

for (int i = 0; i < CallsBetweenTimeChecks; ++i)
{
obj.SayHello();
count += 1;
}
}
Console.WriteLine("Interface: {0} million calls per second", ((double)
count) / 10000000.0);
}
}
Nov 16 '05 #7
Ole Hanson wrote:
I am accessing my database through an interface, to allow future
substitution of the physical datastore - hence I would like to declare
in my Interface that my DAL-objects implementing the interface and
accessing the datastore MUST pass in a UserToken in the constructor
of the object.

Is this not possible?
Am I forced to add the UserToken as a property on the object instead?


The usual solution to this is to define some kind of factory interface,
e.g.:

public interface IDALFactory
{
IDataStoreObject CreateNewObject(UserToken token);
}

or whatever happens to make sense for your particular code.

There are two reasons for doing this:

(1) there is no mechanism in .NET today to impose a constraint that requires
a particular class to provide a particular constructor. Interfaces cannot do
this because interfaces are always purely abstract; since they cannot be
constructed they don't have any notion of constructors. And base classes
can't do this either because for various reasons, derived classes don't
inherit constructors in the same way as normal methods - the only visible
constructors on the derived class are those you write explicitly. The base
class constructors are available to the derived class itself, but they are
not visible as part of its public API. So this:

public class BaseWithCtor
{
public BaseWithCtor(string foo) { }
public BaseWithCtor() { }
}

has two constructors. But this:

public class Derived : BaseWithCtor
{
}

only has the one - it has the compiler-generated default no-params
constructor. But if you try this:

Derived d = new Derived("Hello!");

it doesn't work. Even though the base class has a constructor with this
signature, the derived class doesn't inherit that as part of its public
interface.
(2) the other reason for using a factory interface is that even if the
restrictions in (1) didn't exist, you wouldn't be any better off. Your goal
is to be able to substitute a different implementation in the future. This
means that you can never actually use a constructor in your code directly.
For example, suppose you have this kind of code:

IDataStoreObject obj = new TodaysImplementation(UserToken tok);

then even if some mechanism had been available to enforce the requirement
that TodaysImplementation had that constructor, how does this help you with
TomorrowsImplementation? Even though TomorrowsImplementation might also be
forced to have the right constructor, you're still left with the rather more
fundamental problem that the code above has a hard-coded dependency on the
TodaysImplementation type.

So if you need to be able to substitute in different implementations, you
can't just use the new operator. You're going to have to go via some kind of
factory abstraction to enable the right type to be selected in any case. So
all that matters then is that the factory API takes the parameters you need.
You don't actually need to care how a particular DAL implements the factory.
In particular you won't need to care what constructors are used, so long as
the objects returned by the factory are correctly initialized. Whether this
was done with a particular type of constructor, or with properties or some
other mechanism is an implementation detail of the DAL.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/
Nov 16 '05 #8
Well, in that case I have to apologize if i was wrong.
However, i have read many places that an interface is faster than
an abstract class. This is one of them:
http://www.dotnetspider.com/Technolo...x?SampleId=492

I wont argue with You, but would You also claim that an abstract class
containing only abstract members
is faster than an interface as well? In that case, what is the benefit of
interfaces anyway?

I have always believed interfaces were superior to abstract classes.
I apologie for the misleading information i might have given.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Dennis Myrén" <de****@oslokb.no> wrote in message
news:bP*******************@news4.e.nsc.no...
You need to create 2 class instances
when creating an instance of a class which is derived from an abstract
class.

Creating an instance of an abstract class means performance overhead.
I think that is especially true if the abstract class contains virtual
methods.

Virtual methods always means performance overhead.
According to Microsoft they are two times as expensive as non-virtual
methods.

However, abstract members should be as fast as interface members i believe.
An abstract class containing no virtual methods should be nearly as fast
as an interface, but still slower.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Richard Blewett [DevelopMentor]" <ri******@develop.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
What leads you to the conclusion that interfaces are faster than ABCs?

Regards

Richard Blewett - DevelopMentor

http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<2V*******************@news4.e.nsc.no>

Unfortunately this is not possible.

You may use an abstract class instead which exposes 1 constructor
taking a UserToken though.

I really wished that this was possible, because interfaces are faster

than
abstract classes.

--
Regards,
Dennis JD Myr?n
Oslo Kodebureau
"Ole Hanson" <ol********@ole.ole> wrote in message
news:eg**************@TK2MSFTNGP09.phx.gbl...
> I am accessing my database through an interface, to allow future
> substitution of the physical datastore - hence I would like to
declare in
my
> Interface that my DAL-objects implementing the interface and
accessing the > datastore MUST pass in a UserToken in the constructor of the object.
>
> Is this not possible?
> Am I forced to add the UserToken as a property on the object instead?
>
> /Ole
>
>
>


---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.760 / Virus Database: 509 - Release Date: 10/09/2004

[microsoft.public.dotnet.languages.csharp]


Nov 16 '05 #9
Dennis Myrén <de****@oslokb.no> wrote:
Well, in that case I have to apologize if i was wrong.
However, i have read many places that an interface is faster than
an abstract class. This is one of them:
http://www.dotnetspider.com/Technolo...x?SampleId=492


Well, that talks about JVMs rather than CLRs, so is somewhat dubious to
start with. However, it does say that JVMs are reducing the performance
penalty anyway.

Do you have any evidence that for any app that you've written, the
method call itself has been the bottleneck? I suspect it's a very rare
case where this is actually an issue, even if interface method calls
*are* twice as fast as abstract class method calls (which I'm not
convinced of yet).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10
>Do you have any evidence that for any app that you've written, the
method call itself has been the bottleneck?
No, mr. Skeet. I do not have any evidence for that.
--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Dennis Myrén <de****@oslokb.no> wrote: Well, in that case I have to apologize if i was wrong.
However, i have read many places that an interface is faster than
an abstract class. This is one of them:
http://www.dotnetspider.com/Technolo...x?SampleId=492


Well, that talks about JVMs rather than CLRs, so is somewhat dubious to
start with. However, it does say that JVMs are reducing the performance
penalty anyway.

Do you have any evidence that for any app that you've written, the
method call itself has been the bottleneck? I suspect it's a very rare
case where this is actually an issue, even if interface method calls
*are* twice as fast as abstract class method calls (which I'm not
convinced of yet).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #11
This is to confirm that your test gives about the same results
on my machine.
--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Ian Griffiths" <ia*************@nospam.nospam> wrote in message
news:uK**************@tk2msftngp13.phx.gbl...
Dennis Myrén wrote:
You need to create 2 class instances when creating an instance
of a class which is derived from an abstract class.
No you don't. You end up defining two types, but you only create one
instance.

Here's an example:

public abstract class ABC
{
public abstract void SayHello();
}

public class ConcreteDerived : ABC
{
public override void SayHello() { Console.WriteLine("Hello!"); }
}

And now to use this:

ABC obj = new ConcreteDerived();
obj.SayHello();

I have created just one instance here. I have defined two classes, but

I've only created one instance. (In fact it's impossible to create an instance of the base class, ABC, because it's abstract. So I couldn't create an instance of each even if I wanted to.)

(Note, by the way, that this doesn't actually solve the problem as
originally stated. Abstract Base Classes aren't a solution to this
particular issue because you can't inherit constructor signatures.)

Creating an instance of an abstract class means performance
overhead.
I think that is especially true if the abstract class contains
virtual methods.
You can't create an instance of an abstract class. That's what 'abstract'
means!

Also, the presence of virtual methods has no impact on the overhead of
creating an instance of a class, so your argument is slightly confused

here I'm afraid.

There are overheads to virtual methods, but you've missed an important point here:
Virtual methods always means performance overhead.
According to Microsoft they are two times as expensive as
non-virtual methods.
Yes, but interfaces are even more expensive.

So if you chose to use interfaces instead of abstract base classes to

avoid the overhead of a virtual function call, you've made a bad choice.
Interface method calls are even more expensive than virtual function calls.
The expensive thing is the polymorphic nature of the call. With either
interfaces or virtual methods, the method that ends up getting called will
depend on what type of object you've got, so the JIT-compiled code can't
just call the relevant function directly or inline it. You pay that cost
with either virtual methods or interfaces. And as it happens, interface
method calls are marginally the more expensive of these two call types
today.

(In Whidbey, the next version of .NET, it all gets a little more complex to work out how much a method call costs, because they appear to detect when
you're not actually exploiting polymorphism and change the way the code
works. It's similar to a technique called 'monomorphic inlining' that some
JVMs use. This means that the cost of polymorphic function calls changes
over time.)

However, abstract members should be as fast as interface members i
believe.
Abstract members *are* virtual. If you use ILDASM to look at what the
compiler generates, this becomes very clear. For example, here's the
abstract SayHello method as defined in my ABC class above:

.method public hidebysig newslot abstract virtual
instance void SayHello() cil managed
{
} // end of method ABC::SayHello

Notice that it is marked as 'abstract virtual'. In the IL, this is
explicit. With C#, to save you typing, they don't make you type in both -
abstract methods *have* to be virtual. A non-virtual abstract method makes
no sense: 'abstract' effectively means 'must override', and you can only
override virtual methods. So if you were to define a non-virtual abstract
method you would effectively be defining a method that derived classes

were required to override, but which couldn't be overridden!

So because 'abstract' only makes sense for virtual methods, in C# writing
'abstract' always implies 'virtual'.

So abstract methods are exactly as expensive as virtual methods, for the
simple reason that they *are* virtual methods.

An abstract class containing no virtual methods should be nearly as
fast as an interface, but still slower.
An abstract class containing no virtual methods would be a slightly

unusual thing, because it would contain no abstract methods... It is actually
possible to write such a class, you just wouldn't normall do it. It would
in fact be substantially faster to use than call interface methods, because non-virtual methods (which includes all non-abstract methods) are faster
than either virtual methods or interface method calls. But it wouldn't be a very useful thing - you don't often want to declare an abstract class with
no abstract methods.

But how would an abstract class containing some abstract methods stack up
against an interface? In the current version of the CLR, interface calls are known to be slightly more expensive, so you would expect this:

Fastest: direct call to non-abstract, non-virtual, non-interface methods
2nd fastest: call through abstract or virtual method
Slowest: call through interface method

But it's always important to test, so I wrote a little program that sees how many calls a second I can get through each type. Here are the results:

Direct call: 515 million calls per second
Abstract method: 173 million calls per second
Interface method: 155 million calls per second

That's on my laptop, with a 1.6GHz Pentium M, running v1.1 of the .NET
framework. I've copied the program at the end of this message so you can
try it out.

This seems to confirm that interfaces are (on the current .NET framework)
the slowest of the three options. And for this particular test, a
non-abstract, non-interface call is well over twice as fast.

In any case, not only is this not really relevant to the original discussion (abstract base classes don't help solve the problem any better than
interfaces) this is a bit of a case of micro-optimization. The difference in performance between these different types of method calls is very often
going to be irrelevant - if the method does anything non-trivial, then the
cost of the work it does will swamp any difference between invocation costs. (These distinctions really only matter for very simple methods like
straightforward property accessors. In that case, the main difference is
that with a non-interface and non-virtual call, the JIT compiler can inline the method.)
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/

using System;

public abstract class ABC
{
public abstract void SayHello();
}

public interface IFoo
{
void SayHello();
}

public class ConcreteDerived : ABC
{
public override void SayHello() { }
}

public class InterfaceImpl : IFoo
{
public void SayHello() { }
}

public class NonVirtual
{
public void SayHello() { }
}
class App
{
static void Main()
{
// Run tests multiple times to avoid any transient
// JIT-related overheads

for (int i = 0; i < 5; ++i)
{
SpeedTestNonVirtual(new NonVirtual());
SpeedTestABC(new ConcreteDerived ());
SpeedTestInterface(new InterfaceImpl ());
}
}
const int CallsBetweenTimeChecks = 100000;
static void SpeedTestNonVirtual(NonVirtual obj)
{
DateTime stopBy = DateTime.Now + TimeSpan.FromSeconds(10);
long count = 0;
while (DateTime.Now < stopBy)
{
// Make lots of calls in between time checks, otherwise
// the time take to check the current time dominates.

for (int i = 0; i < CallsBetweenTimeChecks; ++i)
{
obj.SayHello();
count += 1;
}
}
Console.WriteLine("Non-virtual: {0} million calls per second", ((double) count) / 10000000.0);
}

static void SpeedTestABC(ABC obj)
{
DateTime stopBy = DateTime.Now + TimeSpan.FromSeconds(10);
long count = 0;
while (DateTime.Now < stopBy)
{
// Make lots of calls in between time checks, otherwise
// the time take to check the current time dominates.

for (int i = 0; i < CallsBetweenTimeChecks; ++i)
{
obj.SayHello();
count += 1;
}
}
Console.WriteLine("ABC: {0} million calls per second", ((double) count) / 10000000.0);
}

static void SpeedTestInterface(IFoo obj)
{
DateTime stopBy = DateTime.Now + TimeSpan.FromSeconds(10);
long count = 0;
while (DateTime.Now < stopBy)
{
// Make lots of calls in between time checks, otherwise
// the time take to check the current time dominates.

for (int i = 0; i < CallsBetweenTimeChecks; ++i)
{
obj.SayHello();
count += 1;
}
}
Console.WriteLine("Interface: {0} million calls per second", ((double)
count) / 10000000.0);
}
}

Nov 16 '05 #12
> Well, in that case I have to apologize if i was wrong.
However, i have read many places that an interface is faster than
an abstract class. This is one of them:
http://www.dotnetspider.com/Technolo...x?SampleId=492

I wont argue with You,
Please feel free to argue with me. I think it's important to question
pretty much anything you read... (Otherwise, you're liable to be mislead.
There's an awful lot of rubbish out there on the web. That site you linked
to contains false information, for example. Unless you habitually question
everything and work out for yourself what's true, you won't recognize
falsehoods when you see them. I'm pretty sure that I'm right here, but
don't just take my word for it. :-) )

This is why I posted some runnable code that produces real test results in a
repeatable way - I think that's a whole lot more informative than
unjustified rules of thumb that say X is always faster than Y. I may be
right and I may be wrong, but the test shows what the test shows. (My
interpretation of the test results could also be wrong of course. I don't
think it is, but if you see problems, let's discuss them!)

And feel free to pick holes in my test code. It may be that it doesn't
accurately reflect the behaviour you'll see in your code. Ultimately, you
have to test for the kind of work your actual code will be doing. This is
the only reliable way of deciding performance questions. Microbenchmarks
like this aren't all that useful when it comes to writing real code.

but would You also claim that an abstract class containing only abstract
members
is faster than an interface as well? In that case, what is the benefit of
interfaces anyway?


First of all, I think the speed is almost completely irrelevant. The
differences I measured were only on the order of around 10%. But of course
the methods being invoked were empty. In practice, the difference will be
lost in the noise as soon as you put something inside there. (Indeed the
first version of the test I wrote spent more time checking the current time
than it did calling the methods, and there was no measureable performance
difference!)

So for all practical purposes, the difference in speed between abstract base
classes and interfaces is so small that you can ignore it for the vast
majority of scenarios. (And in any case, the difference is smaller still in
the next version of .NET.)

So the right question to be asking is: what fits best for your design? ABCs
or interfaces? Which expresses the structure and concepts in your system
with the most clarity? That's going to be far more important than which runs
fastest for most situations.

So what are the pros and cons?

Interfaces have the distinct benefit that a single class can implement
multiple interfaces. Abstract base classes don't have that feature - you
can only have a single base class. (In fact that's one big reason for
having interfaces at all. In C++, which doesn't restrict you to having a
single base class, there never was any specific notion of an interface,
because you could get exactly the same idiom through the use of abstract
base classes. That's all the COM interfaces were, for example. The only
reason Managed Extensions for C++ introduces interfaces is because the .NET
type system requires it.)

On the other hand, ABCs offer two advantages. First, they enable you to add
in some helper implementation. For example, if you derive from XmlReader,
not only does that mean that your class provides the XmlReader API, it also
means you get a certain amount of help: you are not obliged to implement the
entire thing from scratch.

That's not that great an advantage because you can actually offer this in
conjunction with interfaces - for each interface just declare an optional
base class that provides a partial implementation....

The more important difference with ABCs is that they version better. If you
want to release a new version of an API where you would like to add a new
method to an interface, you can't. If you add a new method, any existing
implementations are now broken, because they don't supply this new method.
But with an ABC, you can supply a default implementation of the method in
the base class. It might throw a NotImplementedException, but that will
only cause a problem if something tries to use the method. Existing code
that didn't even know the method existed clearly isn't going to do that...

The big problem with interfaces here is that they are completely abstract,
and the implementor is obliged to implement everything, and an upshot of
this is that interfaces are effectively immutable - you can't change them
without breaking stuff. (Unless you happen to be in a position to change all
of the classes that implement the interface. And if the interface was
defined as part of some public API, you won't own all the implementations!)

The standard solution was to introduce new interfaces - hence all the
IDispatchEx, IFoobar2, ISpong3 and so on that you see in old COM APIs.

The design guidelines for .NET Framework Class Libraries explicitly
recommend not using interfaces for this very reason. (Brad Abrams, who owns
those guidelines, hates the ISomething2 ISomething3 etc phenomenon and is
keen to avoid it in .NET.)

For what it's worth, I slightly prefer the flexibility interfaces offer. And
since I'm not in the habit of writing platforms that other people use,
versioning of public APIs is not really an issue for me. Interfaces tend to
be internal to my own code, in which case none of the above is really a
problem. If I want to change my interface, I can do that because I own all
the implementations...
So that's why we have both - sometimes one is better, sometimes the other is
better. It depends on what you are doing.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/
Nov 16 '05 #13
Dennis Myrén <de****@oslokb.no> wrote:
Do you have any evidence that for any app that you've written, the
method call itself has been the bottleneck?


No, mr. Skeet. I do not have any evidence for that.


In that case I wouldn't use it as a basis on which to make design
decisions.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #14
Thanks for a really great response, mr. Griffiths.

Interfaces tend to be internal to my own code,
in which case none of the above is really a problem.
If I want to change my interface, I can do that because
I own all the implementations... In my current project, this is very true for me as well.
I have a bunch of objects which implement interface A
defining two methods.
Some of these objects also implement additional functionality
with interface B, which in turn is derived from A.
All these objects should provide that data model,
but still no code can actually be shared between them.
All these objects have completely different implementations
of these interfaces.
Therefore(and in the naive thought that i earned efficiency),
i use interfaces rather than abstract classes for this.

Although these objects implement those interfaces,
actually i more often call the implemented
members on the implementing class itself, rather
than through the interface, i mean i more often do:
[INTERFACE_IMPLEMENTOR].InterfaceMember();
than
[INTERFACE].InterfaceMember();

Therefore, i decided to modify your test program slightly
to better match my current project.

I changed:
static void SpeedTestInterface(IFoo obj)
into:
static void SpeedTestInterface(InterfaceImpl obj)
and also:
static void SpeedTestABC(ABC obj)
into:
static void SpeedTestABC(ConcreteDerived obj)

Somewhat interesting(to me anyway) was that the interface approach
went a lot faster.

This is my most average results running your test with no modification:
Non-virtual: 103,63 million calls per second
ABC: 104,47 million calls per second
Interface: 81,98 million calls per second

And this is my most average results running your test with those
modifications:
Non-virtual: 104,16 million calls per second
ABC: 103,93 million calls per second
Interface: 102,7 million calls per second

Is there a logical explanation for that speed enhancement?

Thanks for great help!

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Ian Griffiths [C# MVP]" <ia*************@nospam.nospam> wrote in message
news:O2**************@TK2MSFTNGP10.phx.gbl...
Well, in that case I have to apologize if i was wrong.
However, i have read many places that an interface is faster than
an abstract class. This is one of them:
http://www.dotnetspider.com/Technolo...x?SampleId=492

I wont argue with You,


Please feel free to argue with me. I think it's important to question
pretty much anything you read... (Otherwise, you're liable to be mislead.
There's an awful lot of rubbish out there on the web. That site you

linked to contains false information, for example. Unless you habitually question
everything and work out for yourself what's true, you won't recognize
falsehoods when you see them. I'm pretty sure that I'm right here, but
don't just take my word for it. :-) )

This is why I posted some runnable code that produces real test results in a repeatable way - I think that's a whole lot more informative than
unjustified rules of thumb that say X is always faster than Y. I may be
right and I may be wrong, but the test shows what the test shows. (My
interpretation of the test results could also be wrong of course. I don't
think it is, but if you see problems, let's discuss them!)

And feel free to pick holes in my test code. It may be that it doesn't
accurately reflect the behaviour you'll see in your code. Ultimately, you
have to test for the kind of work your actual code will be doing. This is
the only reliable way of deciding performance questions. Microbenchmarks
like this aren't all that useful when it comes to writing real code.

but would You also claim that an abstract class containing only abstract
members
is faster than an interface as well? In that case, what is the benefit of interfaces anyway?
First of all, I think the speed is almost completely irrelevant. The
differences I measured were only on the order of around 10%. But of

course the methods being invoked were empty. In practice, the difference will be
lost in the noise as soon as you put something inside there. (Indeed the
first version of the test I wrote spent more time checking the current time than it did calling the methods, and there was no measureable performance
difference!)

So for all practical purposes, the difference in speed between abstract base classes and interfaces is so small that you can ignore it for the vast
majority of scenarios. (And in any case, the difference is smaller still in the next version of .NET.)

So the right question to be asking is: what fits best for your design? ABCs or interfaces? Which expresses the structure and concepts in your system
with the most clarity? That's going to be far more important than which runs fastest for most situations.

So what are the pros and cons?

Interfaces have the distinct benefit that a single class can implement
multiple interfaces. Abstract base classes don't have that feature - you
can only have a single base class. (In fact that's one big reason for
having interfaces at all. In C++, which doesn't restrict you to having a
single base class, there never was any specific notion of an interface,
because you could get exactly the same idiom through the use of abstract
base classes. That's all the COM interfaces were, for example. The only
reason Managed Extensions for C++ introduces interfaces is because the ..NET type system requires it.)

On the other hand, ABCs offer two advantages. First, they enable you to add in some helper implementation. For example, if you derive from XmlReader,
not only does that mean that your class provides the XmlReader API, it also means you get a certain amount of help: you are not obliged to implement the entire thing from scratch.

That's not that great an advantage because you can actually offer this in
conjunction with interfaces - for each interface just declare an optional
base class that provides a partial implementation....

The more important difference with ABCs is that they version better. If you want to release a new version of an API where you would like to add a new
method to an interface, you can't. If you add a new method, any existing
implementations are now broken, because they don't supply this new method.
But with an ABC, you can supply a default implementation of the method in
the base class. It might throw a NotImplementedException, but that will
only cause a problem if something tries to use the method. Existing code
that didn't even know the method existed clearly isn't going to do that...

The big problem with interfaces here is that they are completely abstract,
and the implementor is obliged to implement everything, and an upshot of
this is that interfaces are effectively immutable - you can't change them
without breaking stuff. (Unless you happen to be in a position to change all of the classes that implement the interface. And if the interface was
defined as part of some public API, you won't own all the implementations!)
The standard solution was to introduce new interfaces - hence all the
IDispatchEx, IFoobar2, ISpong3 and so on that you see in old COM APIs.

The design guidelines for .NET Framework Class Libraries explicitly
recommend not using interfaces for this very reason. (Brad Abrams, who owns those guidelines, hates the ISomething2 ISomething3 etc phenomenon and is
keen to avoid it in .NET.)

For what it's worth, I slightly prefer the flexibility interfaces offer. And since I'm not in the habit of writing platforms that other people use,
versioning of public APIs is not really an issue for me. Interfaces tend to be internal to my own code, in which case none of the above is really a
problem. If I want to change my interface, I can do that because I own all the implementations...
So that's why we have both - sometimes one is better, sometimes the other is better. It depends on what you are doing.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/

Nov 16 '05 #15
Hi,

I have always believed interfaces were superior to abstract classes.
I apologie for the misleading information i might have given.


They are two different things, an abstract typemay define some
functionality and let other to be defined by the derived type, an interface
dictate the methods/properties a type MUST implement.

Of course the class define an interface implicitely , IIRC there was a
programming language where you had to explicitly define the interface of a
type, but I may be wrong :)

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Nov 16 '05 #16
Thank you mr. Machin.

I learned something today!

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.machin AT dot.state.fl.us> wrote
in message news:uy**************@tk2msftngp13.phx.gbl...
Hi,

I have always believed interfaces were superior to abstract classes.
I apologie for the misleading information i might have given.
They are two different things, an abstract typemay define some
functionality and let other to be defined by the derived type, an

interface dictate the methods/properties a type MUST implement.

Of course the class define an interface implicitely , IIRC there was a
programming language where you had to explicitly define the interface of a
type, but I may be wrong :)

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Nov 16 '05 #17
Dennis Myrén wrote:

Therefore, i decided to modify your test program slightly
to better match my current project.

I changed:
static void SpeedTestInterface(IFoo obj)
into:
static void SpeedTestInterface(InterfaceImpl obj)
and also:
static void SpeedTestABC(ABC obj)
into:
static void SpeedTestABC(ConcreteDerived obj)

Somewhat interesting(to me anyway) was that the interface approach
went a lot faster.
Have a look at the IL. Before your change, the way that SpeedTestInterface
calls the method is:

callvirt instance void IFoo::SayHello()

but after your change, it looks like this:

callvirt instance void InterfaceImpl::SayHello()

And don't be misled by that 'callvirt' - the 'virt' part doesn't mean what
you might thing. The thing that determines whether virtual, interface, or
basic method dispatch gets used is the nature of the target method.

In the first case, it's calling IFoo.SayHello. And since that's an interface
method, it will be using interface-style dispatch.

But in the second case, notice that it has completely ignored the interface.
(Indeed, you can modify the InterfaceImpl class so that it no longer claims
to implement IFoo without changing the behaviour.) The compiler has done
this because your program no longer relies on the InterfaceImpl class
implementing IFoo. It's just calling the public SayHello method directly.
This is why you get the same performance as you would with any other direct
method call - you really aren't using interfaces in this case. You're
calling a public method. It so happens that the public method is also
available via an interface, but you're not exploiting that here. (As is
easily proved by the fact that removing the interface from the list that
InterfaceImpl implements doesn't stop your version of the program from
working.)

This only works because you made SayHello public. So it's not just there to
implement the IFoo interface, it's also a part of InterfaceImpl's public
face in its own right. It would be different if you had done this:

public class InterfaceImpl : IFoo
{
void IFoo.SayHello() { }
}

This C# syntax says that this method is the implementation of IFoo.SayHello,
but is *not* part of the class's public API. You'll find that if you do
this, your modified version of the test won't work. You'll have to go back
to what I wrote, and it will of course run slower again.
This is my most average results running your test with no modification:
Non-virtual: 103,63 million calls per second
ABC: 104,47 million calls per second
Interface: 81,98 million calls per second
Now that's interesting. Are these really the results you got with the code
exactly as I posted it?

It's interesting because you're getting very different results from me.
(Obviously the results are different partly because we have different
hardware. But what's interesting is the relative differences beween each
type of call.) I get this:

Non-virtual: 510.16 million calls per second
ABC: 170.31 million calls per second
Interface: 155.36 million calls per second

So my non-virtual calls are way faster than the other two. You're finding
the non-virtual runs about the same speed as the ABC calls, which is
completely different from what I got. (So it looks almost as though your
non-virtual case has been slowed down to run at the same speed as the
virtual call.)

So, four questions:

1) Is that definitely the results from the code I posted with no mods at
all?
2) Did you let the test run to completion? The first set of results will
probably be bogus due to JIT compilation transient timing issues. You want
to ignore the first three results and look at the rest it prints out.
3) What version of the .NET framework are you running this on?
4) Are you running in the debugger?
And this is my most average results running your test with those
modifications:
Non-virtual: 104,16 million calls per second
ABC: 103,93 million calls per second
Interface: 102,7 million calls per second

Is there a logical explanation for that speed enhancement?


Yes - the case labelled as "Interface" is no longer really using interfaces
for the reasons described above. But again, your figures look different from
mine. I get this kind of thing with your modifications:

Non-virtual: 512.36 million calls per second
ABC: 172.32 million calls per second
Interface: 515.27 million calls per second

So these are figures that makes sense to me, because with your modifications
to the test, the so-called 'Interface' case isn't using interfaces any more.
It's making a direct call on a method which happens also to be available via
an interface which the code is choosing not to use. So as you'd expect,
it's running at about the same speed as the other 'non-virtual' case. (Give
or take a few percent, which will just be experimental error.)

What I don't understand is why in both your 'before' and 'after' cases, the
ABC case runs roughly as fast as the direct call. I wouldn't expect it to,
and on my system it definitely doesn't! So I'm trying to understand what's
different about your setup and mine.

If you are running in the debugger, try running outside instead. I just
compiled and ran it from the command line.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/
Nov 16 '05 #18
Thanks for the help once again mr. Griffiths.

Yes, I also noticed the strange differences when running your test
and comparing the results to those that you got.
1) Is that definitely the results from
the code I posted with no mods at all? Yes, it is! Very strange indeed.
2) Did you let the test run to completion? The first set of results will
probably be bogus due to JIT compilation transient timing issues. You want
to ignore the first three results and look at the rest it prints out. Yes, i looped five times, and i also repeated the execution of the program 3
times.
I will run once again now, and paste the exact output at the end of this
post
(using your code, absolutely unmodified).
3) What version of the .NET framework are you running this on? I am running .NET Framework v1.1.4322.
4) Are you running in the debugger? Yes, i am running in debug mode from Visual Studio .NET Version 7.1.3088.

INFORMATION ABOUT MY SYSTEM:
Acer Laptop Machine, Intel Pentium M Processor 1700 MHz, 512 MB of RAM
running Windows XP Professional Version 2002 Service Pack 1
EXACT PROGRAM EXECUTION OUTPUT:
Non-virtual: 111,6 million calls per second
ABC: 108,73 million calls per second
Interface: 98,14 million calls per second
Non-virtual: 110,41 million calls per second
ABC: 110,83 million calls per second
Interface: 96,91 million calls per second
Non-virtual: 106,86 million calls per second
ABC: 110,19 million calls per second
Interface: 97,58 million calls per second
Non-virtual: 110,26 million calls per second
ABC: 108,95 million calls per second
Interface: 98,58 million calls per second
Non-virtual: 108,77 million calls per second
ABC: 102,65 million calls per second
Interface: 91,38 million calls per second
Hmm what is wrong with my system.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Ian Griffiths [C# MVP]" <ia*************@nospam.nospam> wrote in message
news:ew**************@TK2MSFTNGP12.phx.gbl... Dennis Myrén wrote:

Therefore, i decided to modify your test program slightly
to better match my current project.

I changed:
static void SpeedTestInterface(IFoo obj)
into:
static void SpeedTestInterface(InterfaceImpl obj)
and also:
static void SpeedTestABC(ABC obj)
into:
static void SpeedTestABC(ConcreteDerived obj)

Somewhat interesting(to me anyway) was that the interface approach
went a lot faster.
Have a look at the IL. Before your change, the way that

SpeedTestInterface calls the method is:

callvirt instance void IFoo::SayHello()

but after your change, it looks like this:

callvirt instance void InterfaceImpl::SayHello()

And don't be misled by that 'callvirt' - the 'virt' part doesn't mean what
you might thing. The thing that determines whether virtual, interface, or
basic method dispatch gets used is the nature of the target method.

In the first case, it's calling IFoo.SayHello. And since that's an interface method, it will be using interface-style dispatch.

But in the second case, notice that it has completely ignored the interface. (Indeed, you can modify the InterfaceImpl class so that it no longer claims to implement IFoo without changing the behaviour.) The compiler has done
this because your program no longer relies on the InterfaceImpl class
implementing IFoo. It's just calling the public SayHello method directly.
This is why you get the same performance as you would with any other direct method call - you really aren't using interfaces in this case. You're
calling a public method. It so happens that the public method is also
available via an interface, but you're not exploiting that here. (As is
easily proved by the fact that removing the interface from the list that
InterfaceImpl implements doesn't stop your version of the program from
working.)

This only works because you made SayHello public. So it's not just there to implement the IFoo interface, it's also a part of InterfaceImpl's public
face in its own right. It would be different if you had done this:

public class InterfaceImpl : IFoo
{
void IFoo.SayHello() { }
}

This C# syntax says that this method is the implementation of IFoo.SayHello, but is *not* part of the class's public API. You'll find that if you do
this, your modified version of the test won't work. You'll have to go back
to what I wrote, and it will of course run slower again.
This is my most average results running your test with no modification:
Non-virtual: 103,63 million calls per second
ABC: 104,47 million calls per second
Interface: 81,98 million calls per second
Now that's interesting. Are these really the results you got with the

code exactly as I posted it?

It's interesting because you're getting very different results from me.
(Obviously the results are different partly because we have different
hardware. But what's interesting is the relative differences beween each
type of call.) I get this:

Non-virtual: 510.16 million calls per second
ABC: 170.31 million calls per second
Interface: 155.36 million calls per second

So my non-virtual calls are way faster than the other two. You're finding
the non-virtual runs about the same speed as the ABC calls, which is
completely different from what I got. (So it looks almost as though your
non-virtual case has been slowed down to run at the same speed as the
virtual call.)

So, four questions:

1) Is that definitely the results from the code I posted with no mods at
all?
2) Did you let the test run to completion? The first set of results will
probably be bogus due to JIT compilation transient timing issues. You want to ignore the first three results and look at the rest it prints out.
3) What version of the .NET framework are you running this on?
4) Are you running in the debugger?
And this is my most average results running your test with those
modifications:
Non-virtual: 104,16 million calls per second
ABC: 103,93 million calls per second
Interface: 102,7 million calls per second

Is there a logical explanation for that speed enhancement?
Yes - the case labelled as "Interface" is no longer really using

interfaces for the reasons described above. But again, your figures look different from mine. I get this kind of thing with your modifications:

Non-virtual: 512.36 million calls per second
ABC: 172.32 million calls per second
Interface: 515.27 million calls per second

So these are figures that makes sense to me, because with your modifications to the test, the so-called 'Interface' case isn't using interfaces any more. It's making a direct call on a method which happens also to be available via an interface which the code is choosing not to use. So as you'd expect,
it's running at about the same speed as the other 'non-virtual' case. (Give or take a few percent, which will just be experimental error.)

What I don't understand is why in both your 'before' and 'after' cases, the ABC case runs roughly as fast as the direct call. I wouldn't expect it to, and on my system it definitely doesn't! So I'm trying to understand what's different about your setup and mine.

If you are running in the debugger, try running outside instead. I just
compiled and ran it from the command line.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/

Nov 16 '05 #19
Dennis Myrén wrote:
4) Are you running in the debugger? Yes, i am running in debug mode from Visual Studio .NET
Version 7.1.3088.


OK, it's a debug thing.

I get the same results as you when I run in the debugger. (And not just
relative speeds - I get more or less exactly the same figures, which is
hardly surprising given how similar our systems are.)

Hmm what is wrong with my system.

Nothing. Compile for Release mode and run outside the debugger, and you
should see the same results as me.

I'm not quite sure why building for Debug mode is doing this, but I know the
JIT compiler generates different code when the code is compiled for Debug
mode. It'll disable inlining I expect, which may account for most of the
difference. The results are still a little surprising, nonetheless. But
perf tends to go out of the window in debug builds, so it's wise not to use
that to do any kind of perf tests...
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/
Nov 16 '05 #20
Hi.

Yes, as I switched to RELEASE mode my results went similar to your results.
But perf tends to go out of the window in debug builds,
so it's wise not to use that to do any kind of perf tests... Indeed. It is just, i assumed that was what you were doing.

Thank you for your help.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Ian Griffiths [C# MVP]" <ia*************@nospam.nospam> wrote in message
news:%2***************@tk2msftngp13.phx.gbl... Dennis Myrén wrote:
4) Are you running in the debugger? Yes, i am running in debug mode from Visual Studio .NET
Version 7.1.3088.


OK, it's a debug thing.

I get the same results as you when I run in the debugger. (And not just
relative speeds - I get more or less exactly the same figures, which is
hardly surprising given how similar our systems are.)

Hmm what is wrong with my system.

Nothing. Compile for Release mode and run outside the debugger, and you
should see the same results as me.

I'm not quite sure why building for Debug mode is doing this, but I know

the JIT compiler generates different code when the code is compiled for Debug
mode. It'll disable inlining I expect, which may account for most of the
difference. The results are still a little surprising, nonetheless. But
perf tends to go out of the window in debug builds, so it's wise not to use that to do any kind of perf tests...
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/

Nov 16 '05 #21

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

Similar topics

5
by: Carlos Ribeiro | last post by:
Hello all, I'm posting this to the list with the intention to form a group of people interested in this type of solution. I'm not going to spam the list with it, unless for occasional and...
21
by: Steve - DND | last post by:
I know it's possible to require inheriting classes to implement a particular function or property, but is it possible to require a inheriting class to implement a constructor of it's own? ...
10
by: linkspeed | last post by:
Following texts are from C# spec. The optional constructor-initializer specifies another instance constructor to invoke before executing the statements given in the constructor-body of this...
4
by: Peter | last post by:
I want to copy a parent class instance's all datas to a child's. It's actually a C++'s copy constructor. But why the following code does not work - there is a compile error! How it should look...
14
by: Arne | last post by:
In C++ we have a copy constructor. What is the equivalent in .Net? Would that be a clone method?
15
by: CR | last post by:
I've noticed that the trend these days is to declare variables in the middle of code instead of at the top. What is the advantage of this? It seems like it makes it hard to reuse variables. Here...
1
by: Ruffin Bailey | last post by:
I want to declare an interface that forces the presence of a certain constructor (in this case, "Sub New(ByVal ds As DataSet)"). When I try, I get a 'Sub New' cannot be declared in an...
10
by: AZRebelCowgirl73 | last post by:
This is what I have so far: My program! import java.util.*; import java.lang.*; import java.io.*; import ch06.lists.*; public class UIandDB {
2
by: gilbert | last post by:
Hello. I am trying to use c# generic to define a class. class MyClass<Twhere T: new(){ } In this definition, MyClass can create T objects with a default constructor. Is there any way to...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.