Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use byte or int?

Tags:

c#

asp.net

I recall having read somewhere that it is better (in terms of performance) to use Int32, even if you only require Byte. It applies (supposedly) only to cases where you do not care about the storage. Is this valid?

For example, I need a variable that will hold a day of week. Do I

int dayOfWeek; 

or

byte dayOfWeek; 

EDIT: Guys, I am aware of DayOfWeek enum. The question is about something else.

like image 339
niaher Avatar asked Feb 27 '10 05:02

niaher


People also ask

Why do we use int instead of byte?

Performance-wise, an int is faster in almost all cases. The CPU is designed to work efficiently with 32-bit values. Shorter values are complicated to deal with. To read a single byte, say, the CPU has to read the 32-bit block that contains it, and then mask out the upper 24 bits.

When would you use a byte?

A byte is the unit most computers use to represent a character such as a letter, number or typographic symbol. Each byte can hold a string of bits that need to be used in a larger unit for application purposes. As an example, a stream of bits can constitute a visual image for a program that displays images.

Are bytes faster than ints?

No. Not in terms of performance anyway. (There are some methods in Integer , Long , etc for dealing with int , long , etc as unsigned. But these don't give any performance advantage.

What is the difference between int and byte?

A byte is the format data is stored in memory in past. 8 bits. An int is a format likewise you get it as value from the accumulator.


2 Answers

Usually yes, a 32 bit integer will perform slightly better because it is already properly aligned for native CPU instructions. You should only use a smaller sized numeric type when you actually need to store something of that size.

like image 55
MikeP Avatar answered Sep 18 '22 17:09

MikeP


You should use the DayOfWeek enum, unless there's a strong reason not to.

DayOfWeek day = DayOfWeek.Friday; 

To explain, since I was downvoted:

The correctness of your code is almost always more critical than the performance, especially in cases where we're talking this small of a difference. If using an enum or a class representing the semantics of the data (whether it's the DayOfWeek enum, or another enum, or a Gallons or Feet class) makes your code clearer or more maintainable, it will help you get to the point where you can safely optimize.

int z; int x = 3; int y = 4; z = x + y; 

That may compile. But there's no way to know if it's doing anything sane or not.

Gallons z; Gallons x = new Gallons(3); Feet y = new Feet(4); z = x + y; 

This won't compile, and even looking at it it's obvious why not - adding Gallons to Feet makes no sense.

like image 23
kyoryu Avatar answered Sep 19 '22 17:09

kyoryu