user4282669
user4282669

Reputation:

Does converting UInt8(or similar types) to Int counter the purpose of UInt8?

I'm storing many of the integers in my program as UInt8, having a 0 - 255 range of values. Now later on I will be summing many of them to get a result that will be able to be stored into an Int. Does this conversion I have to do before I add the values from UInt8 to Int defeat the purpose of me using a smaller datatype to begin with? I feel it would be faster to just use just Int, but suffer larger a memory footprint. But why go for UInt8 when I have to face many conversions reducing of speed and increasing memory as well. Is there something I'm missing, or should smaller datatypes be really only used with other small datatypes?

Upvotes: 0

Views: 263

Answers (1)

Code Different
Code Different

Reputation: 93181

You are talking a few bytes per variable when storing as UInt8 instead of Int. These data types were conceived very early on in the history of computing, when memory was measured in the low KBs. Even the Apple Watch has 512MB.

Here's what Apple says in the Swift Book:

Unless you need to work with a specific size of integer, always use Int for integer values in your code. This aids code consistency and interoperability. Even on 32-bit platforms, Int can store any value between -2,147,483,648 and 2,147,483,647, and is large enough for many integer ranges.

I use UInt8, UInt16 and UInt32 mainly in code that deals with C. And yes, converting back and forth is a pain in the neck.

Upvotes: 1

Related Questions