The Python Oracle

CharField max_length 2^n vs 2^n-1

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon

--

Chapters
00:00 Question
01:09 Accepted answer (Score 10)
02:12 Thank you

--

Full question
https://stackoverflow.com/questions/7233...

Question links:
[2048 seems to be more popular than 2047]: http://www.googlefight.com/index.php?lan
[255 is more popular than 256]: http://www.googlefight.com/index.php?lan
[max_length is restricted to 255 characters if you are using unique=True]: https://docs.djangoproject.com/en/dev/re...

Accepted answer links:
[sometimes be stored more efficiently]: https://stackoverflow.com/questions/2340...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #database #django

#avk47



ACCEPTED ANSWER

Score 11


You've mostly got it. It's not just the unique=True argument for 255, it's also that strings up to 255 long can sometimes be stored more efficiently.

So the answer is that there is maybe a point to doing it for 255 vs. 256, but for other lengths it's very likely to be pointless. Picking power-of-two lengths to begin with is often not done for a scientific reason (most of us haven't actually benchmarked that our 512-long field made our application run measurably faster than a 513-long field).

That said, there may be application-specific cases where the Django application is a frontend to a C application, where having N^2-1 strings is useful further down the line to efficiently store the additional terminating \0 byte.