Skip to content

Optimise Rng::gen for arrays #1282

@dhardy

Description

@dhardy

Summary

Currently, rng.gen::<[u8; 4]>() will invoke the RNG four times. In contrast, rng.fill(&mut array) would do so once. Ideally we should optimise the former to do the same as the latter.

Details

Fill only supports arrays and slices over a few types:

  • bool, char, f32, f64: these invoke rng.gen() for each element (wasteful for bool, but required for the rest)
  • u8: straight byte copy
  • Other integer types: byte copy + to_le (for portability)

rng.gen() does not support slices (unsized) but supports arrays over anything supported by the Standard distribution.

We could:

  1. Keep things as they are: each method has its advantages, but it's confusing that rng.fill(&mut array) is not equivalent to array = rng.gen().
  2. Aim to use specialization to use the Fill method where possible. But who knows when Rust will support this.
  3. Limit rng.gen() to types supported by Fill (API breaking change). We can try to support enough types to satisfy most users, but cannot support user-defined types.

If we choose (3), we could extend this such that both methods support all generable element types once Specialization is stable.

Motivation

  • Intuitive behaviour: it's not intuitive that one method is potentially much faster than the other and generates different results
  • Performance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions