The optimality of word lengths. Theoretical foundations and an empirical study