Rust 向量(`Vec<T>`)与数组(`[T; n]`)的性能 [英] Performance of Rust vector (`Vec&lt;T&gt;`) versus array (`[T; n]`)

查看:142
本文介绍了Rust 向量(`Vec<T>`)与数组(`[T; n]`)的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rust 中使用向量与数组相比,我在性能方面损失了多少?

How much am I losing in terms of performance when using a vector versus an array in Rust?

性能我的意思是:元素访问速度或迭代速度.

By performance I mean: speed of element access or speed of iteration.

推荐答案

它们都将数据存储在线性连续数组中,其中访问或迭代都是 O(1) 操作,因此性能没有差异.vector 较慢的唯一情况可能是一些小列表,因为数组存储在当前堆栈帧的堆栈中,因此它们的数据很可能已经加载到 CPU 缓存中.Vector OTOH 将数据存储在堆上,因此数据在第一次访问之前不会在缓存中可用

They both store data in a linear contiguous array where accessing or iterating is both an O(1) operation so there's no difference in performance. The only case when vector is slower is probably for some small lists because array is stored on stack in the current stack frame, hence their data is highly probably already loaded to the CPU cache. Vector OTOH stores data on the heap so data will not be available in cache before they're first accessed

Vector 还有一层重定向,因为你需要先加载数组的地址,所以第一次内存访问可能会更慢,但这可以忽略不计

Vector also has one more level of redirection because you need to load the address of the array first so the first memory access may also be slower, but that's just negligible

vector 更糟糕的另一种情况是,当您使用 vector 向量 vs 多维数组时,因为每个向量都是单独分配的,并且遍布内存,这不利于缓存.参见vec vs array的访问时间

The other time when vector is much worse is when you use a vector of vector vs a multidimensional array because each vector is allocated separately and lies all around memory which is not good for caching. See Access time of vec vs array

另见 array 与 vec 在内存和 CPU 使用率方面的区别

这篇关于Rust 向量(`Vec<T>`)与数组(`[T; n]`)的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆