Skip to content

Commit f4dfb76

Browse files
authored
Rollup merge of #87609 - LukasKalbertodt:improve-array-map-docs, r=m-ou-se
Add docs about performance and `Iterator::map` to `[T; N]::map` This suboptimal code gen for some usages of array::map got a bit of attention by multiple people throughout the community. Some cases: - #75243 (comment) - #75243 (comment) - https://www.reddit.com/r/rust/comments/oeqqf7/unexpected_high_stack_usage/ My *guess* is that this gets the attention it gets because in JavaScript (and potentially other languages), a `map` function on arrays is very commonly used since in those languages, arrays basically take the role of Rust's iterator. I considered explicitly naming JavaScript in the first paragraph I added, but I couldn't find precedence of mentioning other languages in standard library doc, so I didn't add it. When array::map was stabilized, we still wanted to add docs, but that somehow did not happen in time. So here we are. Not sure if this sounds crazy but maybe it is worth considering beta backporting this? Only if it's not a lot of work, of course! But yeah, stabilized array::map is already in beta and if this problem is really as big as it sometimes seems, might be worth having the docs in place when 1.55 is released. CC ``@CryZe`` r? ``@m-ou-se`` (since you were involved in that discussion and the stabilization)
2 parents 2bdc54f + 5cc7702 commit f4dfb76

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

library/core/src/array/mod.rs

+22
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,28 @@ impl<T, const N: usize> [T; N] {
293293
/// Returns an array of the same size as `self`, with function `f` applied to each element
294294
/// in order.
295295
///
296+
/// If you don't necessarily need a new fixed-size array, consider using
297+
/// [`Iterator::map`] instead.
298+
///
299+
///
300+
/// # Note on performance and stack usage
301+
///
302+
/// Unfortunately, usages of this method are currently not always optimized
303+
/// as well as they could be. This mainly concerns large arrays, as mapping
304+
/// over small arrays seem to be optimized just fine. Also note that in
305+
/// debug mode (i.e. without any optimizations), this method can use a lot
306+
/// of stack space (a few times the size of the array or more).
307+
///
308+
/// Therefore, in performance-critical code, try to avoid using this method
309+
/// on large arrays or check the emitted code. Also try to avoid chained
310+
/// maps (e.g. `arr.map(...).map(...)`).
311+
///
312+
/// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
313+
/// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
314+
/// really need a new array of the same size as the result. Rust's lazy
315+
/// iterators tend to get optimized very well.
316+
///
317+
///
296318
/// # Examples
297319
///
298320
/// ```

0 commit comments

Comments
 (0)