Add note about TLS lookups in random()

Fixes #16072
This commit is contained in:
Steve Klabnik 2015-01-12 17:57:28 -05:00
parent b21a6da340
commit 6a7f0a99d8
1 changed files with 26 additions and 1 deletions

View File

@ -374,9 +374,13 @@ impl Rng for ThreadRng {
/// `random()` can generate various types of random things, and so may require
/// type hinting to generate the specific type you want.
///
/// This function uses the thread local random number generator. This means
/// that if you're calling `random()` in a loop, caching the generator can
/// increase performance. An example is shown below.
///
/// # Examples
///
/// ```rust
/// ```
/// use std::rand;
///
/// let x = rand::random();
@ -389,6 +393,27 @@ impl Rng for ThreadRng {
/// println!("Better lucky than good!");
/// }
/// ```
///
/// Caching the thread local random number generator:
///
/// ```
/// use std::rand;
/// use std::rand::Rng;
///
/// let mut v = vec![1, 2, 3];
///
/// for x in v.iter_mut() {
/// *x = rand::random()
/// }
///
/// // would be faster as
///
/// let mut rng = rand::thread_rng();
///
/// for x in v.iter_mut() {
/// *x = rng.gen();
/// }
/// ```
#[inline]
pub fn random<T: Rand>() -> T {
thread_rng().gen()