CharField max_length 2 ^ n vs 2 ^ n-1

Why is using max_length CharField equal to 2 ^ n while others use 2 ^ n-1?

For example:

  • in django.contrib.gis.db.backends.postgis.models (django 1.3):

    class SpatialRefSys(models.Model, SpatialRefSysMixin): srtext = models.CharField(max_length=2048) 
  • in django_openid_auth.models (djano-openid-auth 0.3):

     class Nonce(models.Model): server_url = models.CharField(max_length=2047) 

Although this is not a scientific measure, 2048 seems more popular than 2047 , but 255 is more popular than 256 . The Django documentation says that in MySQL max_length is limited to 255 characters if you use unique = True . But why use 2 ^ n-1 instead of od 2 ^ n in other cases?

+7
source share
1 answer

You basically got it. This is not just a unique argument = True for 255, but also longer strings up to 255 ( ) in length .

So the answer is that it might make sense to do this for 255 versus 256, but for other lengths it will most likely be pointless. The choice of power for two lengths for a start is often not carried out for a scientific reason (most of us did not actually compare that our 512-long field made our application run much faster than a field of 513 length).

However, there may be cases specific to the application, where the Django application is the interface to the application C, where the line N ^ 2-1 is useful further down the line for efficient storage of the additional trailing byte \0 .

+6
source

All Articles