Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

varchar Fields - Is a Power of Two More Efficient?

Is it more efficient to use a varchar field sized as a power of two vs. another number? I'm thinking no, because for SQL Server the default is 50.

However, I've heard (but never confirmed) that sizing fields as a power of 2 is more efficient because they equate to even bytes, and computers process in bits & bytes.

So, does a field declared as varchar(32) or varchar(64) have any real benefit over varchar(50)?

like image 453
HardCode Avatar asked Feb 27 '09 03:02

HardCode


People also ask

Is varchar faster than text?

Some Differences Between VARCHAR and TEXT A VARCHAR can be part of an index whereas a TEXT field requires you to specify a prefix length, which can be part of an index. VARCHAR is stored inline with the table (at least for the MyISAM storage engine), making it potentially faster when the size is reasonable.

Does varchar Max affect performance?

In addition, varchar(max) prevents the ability to perform online indexes against the entire table which contains the varchar(max) field. This will significantly impact performance of your system.

What is the difference between varchar and varchar Max?

If you use char or varchar, we recommend to: Use char when the sizes of the column data entries are consistent. Use varchar when the sizes of the column data entries vary considerably. Use varchar(max) when the sizes of the column data entries vary considerably, and the string length might exceed 8,000 bytes.

Why do we use varchar 255?

1 byte for the length, and the actual storage for the rest. 255 is the max limit, not an allocation. 255 is not the max limit. There is a variable MAX you can use which Varchar(max) stores a maximum of 2 147 483 647 characters.


2 Answers

No.

In some other uses, there are some advantages to use structures with a power of two size, mostly because you can fit a nice (power of two) number of these inside another power-of-two-sized structure. But this doesn't apply to a DB fieldsize.

The only power-of-two-sizing related to VARCHARs is about the exact type of varchar (or TEXT/BLOB in some SQL dialects): if it's less than 256, it can use a single byte to indicate length. if it's less than 65536 (64KB), two bytes are enough, three bytes work up to 16777216 (16MB), four bytes go to 4294967296 (4GB).

Also, it can be argued that VARCHAR(50) is just as expensive as VARCHAR(255), since both will need n+1 bytes of storage.

Of course that's before thinking of Unicode...

like image 68
Javier Avatar answered Oct 02 '22 18:10

Javier


I always thought people choose powers of two for varchar fields because we're geeks and that's what we do. At least that's what I've always done.

like image 43
Paul Tomblin Avatar answered Oct 02 '22 16:10

Paul Tomblin