A simple solution is
UUID.randomUUID().toString().replace("-", "")
(Like existing solutions, this only avoids calling String # replaceAll . There is no need to replace the regular expression here, so String # replace feels more natural, although technically it still does with regular expressions. Given that generating UUIDs is more expensive than replacement should not be a significant difference in lead time.)
Using the UUID class is probably fast enough for most scenarios, although I would expect some specialized handwriting option that does not require postprocessing to be faster. In any case, the bottleneck of general computation will usually be a random number generator. In the case of the UUID class, it uses SecureRandom .
Which random number generator to use is also a trade-off, which depends on the application. If it is security sensitive, SecureRandom is generally recommended. Otherwise, ThreadLocalRandom is an alternative (faster than SecureRandom or old Random , but not cryptographically secure).
Philipp ClaΓen Sep 07 '16 at 23:55 2016-09-07 23:55
source share