NoSql: Enums vs Strings
Just curious how others deal with开发者_如何学编程 enums & nosql? Is it better to store an attribute as an enum value or a string? Does this affect the size or performance of the database in some cases? For example, just think of, let's say, a pro sports player... his sport type could be Football, Hockey, Baseball, Basketball, etc... string vs enum, what do you all think?
You should be using enums in your code - strong typing helps avoid a lot of mistakes - and converting them to strings or numbers for storage.
Strings do require significantly more storage space - "Basketball" is 10-20 bytes depending on encoding, and if you store it as 4 it only needs 1 byte. However, there are very few cases where this will actually matter - if you have a million records, it is still less than 20MB difference in total database size. Strings are easier to work with and less likely to fail silently if the enumeration changes, so use strings.
Strings are also slower than numbers for most operations, including conversion to enum on load. However, the difference is orders of magnitude less than the time taken to retrieve anything at all from the database, so doesn't matter.
String
are better of portability perspective. And Enum
is not supported by popular DBMS's like MSSQL Server
and many others.
You can have application level logic to prevent valid input against an array and just store it as String.
EDIT:
My preferences changed to String
as CakePHP
(where I do web apps) no-longer support Enum
for portability concerns.
精彩评论