Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using smallint datatype over int in mysql actually save memory?

Tags:

mysql

Does using a smallint datatype in a mysql table over a regular int actually improve memory usage? Wouldn't the hardware just allocate a full 64 bit word size for all data anyway? If it doesn't allocate a full word, then wouldn't we see a performance decrease from having to parse out multiple smallints or tinyints from a 64 bit word allocated in memory?

Basically, is there any design/memory/performance benefit to using the following table over the one after it, assuming we know the range of the values stored in the Status column will never exceed the max/min range of smallint? Any insight would be appreciated:

create table `TestTableWithSmallInt` (
  `ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `Status` smallint(11) DEFAULT 0,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

create table `TestTableWithInt` (
  `ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `Status` int(11) DEFAULT 0,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
like image 485
encrest Avatar asked Sep 26 '13 21:09

encrest


People also ask

What is the difference between Int and Smallint in SQL?

While INT lets you have up to 4 bytes per entry, SMALLINT limits you to 2. 2 x 8 = 16, so as a result, you only have a range of 65,536 (2^16) different numbers.

What is Smallint in MySQL?

SMALLINT is a small integer. The SMALLINT range for SIGNED values is from -32768 to 32767. The minimum and maximum values for SMALLINT UNSIGNED are 0 and 65535 respectively. The size is 2 bytes per row.


2 Answers

You'll theoretically save two bytes per row, a SMALLINT is a 16-bit signed integer versus the INT which is 32-bit signed. The various types have varying storage requirements.

Normally the savings between INT and SMALLINT produces such a slim performance improvement that you'll have a hard time measuring it, especially if there's a small number of fields you're trimming this way.

For the opposite, you'll only want to use a BIGINT when it's conceivable that you might exhaust the number space of an AUTO_INCREMENT flagged field.

You should probably declare them in their bare types, without a length, to get the best fit. INT is preferable to INT(11) and SMALLINT(11) is misleading as it's impossible to get that much precision from a 16-bit value.

like image 156
tadman Avatar answered Sep 21 '22 06:09

tadman


Data shoveling of compact memory blocks is faster. Only when a programming language comes into play, conversion takes place.

like image 24
Joop Eggen Avatar answered Sep 19 '22 06:09

Joop Eggen