In my web app I have a chatroom. I wish to have each user's name to be colored differently rather than having them all black. What is the best way to achieve this? Should I store the RGB/HEX code for each user as they sign up to my app and put that string as a field as part of their record in the database?
Generate your colors from HSV/HSL using the hue value in particular. Then convert to RGB.
See my answer here for more information on HSV/HSL
You probably want as different as possible colors each time.
You could do this by keeping a queue of color ranges.
If the queue is empty return hue 0 and insert the pair (0, 360) into the queue. Next time you want a color pop an element from the queue (0, 360), and return the mid point between those values: 180. Then push (0, 180) and (180, 360) into the queue.
Next time you want a color pop an element from the queue (0, 180), and return the mid point between those values: 90. Then push (0, 90) and (90, 180) into the queue.
Next time you want a color pop an element from the queue (180, 360), and return the mid point between those values: 270. Then push (180, 270) and (270, 360) into the queue.
Continue this process...
You will have the widest possible distinguishable colors for each user automatically.
I'd have a fixed list of colours and get the users to pick from that and store an index in the database, 1 = red
, 2 = green
etc. This would allow you to change the shade of each colour to match the design of your site as it evolves.
For example, you might want the "red" to match the same red as your logo; if you've stored this as an RGB value in your database rather than just "red" it will be much harder to change.
If your goal is to make the user distinguishable at a glance within the chat room, it depends on how large your user base is. If the average size of a chat room is, say, 10, but your user base is in the thousands, having a unique color for each of them is not going to work. Eventually you would end up with slightly different shades of the same color showing up in the same chat room.
In that case just keep a short list of blatantly different colors and assign them within the single chat room.
As an alternative to your scheme:
You can do it like irssi (and others do), and just assign color based on the hash (using your function of choice) of the screen nick. Length of nick and color (should / will) be uncorrelated under this system, so the combination of different letters, different screen names, and different colors should be enough to make things both distinguishable, but consistent from session to session. In this scheme, this only thing you might have to cache is within as session the color for each user name, so you don't have to do zillions of md5 calls. This doesn't guarantee a different color for each user (far from it), and maybe you should think about the purposes you're trying to achieve with that specification.