Is using `int` more preferable than using `unsigned int`?

I have a code where I am using data-types such as int, unsignedint, and unsigned char. How beneficial/futile (in terms of memory/speed) will the activity of changing all the data-types to int be?

  • The code has several structures defined having bytes,int, char inside them. Will it bring any performance improvements in terms of memory/speed considering structure padding and other factors?

  • Answer:

    Please note that you can only save memory by using packed structures, but when you use packed structure you actually lose speed, because depending on the architecture, the CPU can read only 4-8 bytes aligned to multiple of 4/8 addresses. Again, this is dependent on the architecture. You save some memory, so if your work requires huge cache of data then you may want to use the benefits of this structure packing. You may save some speed when copying (via memcpy) large chunks of data (you copy less bytes). But otherwise, in real 'work' accessing the data will become slightly slower, because, for example, the CPU will bring and int into memory and isolate the char from the rest of the 'garbage'. Also with packed structures you might have race conditions when writing the same structure, but different fields. Otherwise, by default, the compiler decides on how to pack your data structures. Usually it makes sensible choices. A very interesting reading is Ulrich Drepper's paper: What every programmer should know about memory. http://www.akkadia.org/drepper/cpumemory.pdf

Dorin Lazăr at Quora Visit the source

Was this solution helpful to you?

Other answers

4 consecutive "char" in a struct will take only 4 bytes, so you would save memory. If a "char" is between two "int" it will also take 4 bytes just by itself because of padding as the following int needs to be aligned. So yes, you can save memory by using char, short and bools instead of int. Of course, it will only matter if you have millions of these objects.

Gregory Popovitch

In addition to what Dorin and Gregory said: Modern systems are so complex that it's nearly impossible to make a prediction. Implement, measure performance, tweak, repeat.

Vlad Petric

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.