0

I apologize in advance if I have grammar mistakes - English is not my strong side. :)

I am trying to create a code in C# which has 2 variables that represents time: The first contains hours, and the second contains minutes.

My question is simple - what datatype should I use for those variables? on one hand, I should use byte, because hours and minutes are between 0 and 255, but on the other hand - I have read that the CPU works better with int. So which one should I use?

Here is the answer I have read which compares between int and byte from the perspective of CPU performance: Why should I use int instead of a byte or short in C#

Thank you for your assistance!

Community
  • 1
  • 1
Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • possible duplicate of [Should I use byte or int?](http://stackoverflow.com/questions/2346394/should-i-use-byte-or-int) – Jcl Feb 18 '15 at 08:15
  • 1
    And yes, past the 8 bit processor era, it's generally not "faster" to use 8 bits. It may help with storage, but not with speed. – Jcl Feb 18 '15 at 08:17

3 Answers3

2

TimeSpan struct is the standard way of representing times in .Net. However, you can work also with int or byte to represent seconds, minutes, etc. too. byte has an smaller footprint then int, but it shouldn't make a big difference.

https://msdn.microsoft.com/en-us/en-en/library/system.timespan(v=vs.110).aspx

unarist
  • 616
  • 8
  • 26
Oscar
  • 13,594
  • 8
  • 47
  • 75
1

You don't need two different variables for this. Use the dedicated TimeSpan type for this purpose.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • My question is more general. If I have a variable that represent small numbers - what datatype should I use? Thank you very much! – Michael Haddad Feb 18 '15 at 08:17
  • 3
    @Sipo That's not what you asked. Look at your question *What type should be used for representing time in C#?* – Sriram Sakthivel Feb 18 '15 at 08:18
  • You are right. I ment that I would still like to have an answer for the general case. English problems, sorry. :) – Michael Haddad Feb 18 '15 at 08:20
  • 1
    @Sipo ok, for general question, you need to find which range your number will fit in. If it fits inside `byte` use `byte`. If it fits short, use short and so forth. – Sriram Sakthivel Feb 18 '15 at 08:22
1

It depends on your system requirement. If you're developing an application for Windows desktop or server, you can expect that you will have a lot of RAM.

So you can use System.Int32, cause modern CPUs are optimized for this type processing.

If you're developing an application for mobile platform or for embedded devices, then an amount of RAM can be limited, where limit can be 512Mb or 1Gb. So if you aren't creating millions of such objects, you can use System.Int32 again.

Finally, if you want serialize and de-serialize these objects, you may cast them to System.Byte at the serialization step.

Mark Shevchenko
  • 7,937
  • 1
  • 25
  • 29