Enum vs Constants performance

F

farseer

if an enum requires boxing often, i'd assume constants would win on
performance, is that true?

Further, it appears that if you need to pass enum values to functions
that accept only uint, int or byte (therefore, you also must unbox and
cast the enums to the type it "inherits" from) quite often, then
constants may be a better choice if performance is an issue.

Are these assumptions correct?
 
M

Mattias Sjögren

if an enum requires boxing often, i'd assume constants would win on
performance, is that true?

Why would enums require boxing more often than constant integer values
(I assume thatäs the alternative you mean)?


Mattias
 
J

Jon Skeet [C# MVP]

farseer said:
if an enum requires boxing often, i'd assume constants would win on
performance, is that true?

Further, it appears that if you need to pass enum values to functions
that accept only uint, int or byte (therefore, you also must unbox and
cast the enums to the type it "inherits" from) quite often, then
constants may be a better choice if performance is an issue.

Are these assumptions correct?

Firstly, as Mattias says, there's no more boxing involved with enums
than with value-type constants. Casting an enum to an int doesn't box
or unbox it, for instance.

Secondly, even if there were some slight performance improvement from
using a constant compared with an enum, I'd *prove* that it was
actually significant in the system before moving to a less strongly
type for the sake of performance.

It's quite possible for performance to an issue, but for it still not
to be worth micro-optimising.
 
J

John Mark Howell

If you're concerned about boxing, then simply define your enum of the most common type. For example:
public enum MyEnum : uint {entry1 = 1,entry2 = 2,entry3 = 3}
 

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

Top