我正在使用Rust构建Game Boy模拟器。我创建了一个readByteFromMemory()函数,它以一个8KB的数组作为参数,表示Game Boy的内部存储器大小为8KB。我在这里考虑两个选项:
fn readByteFromMemory(internalRAM: [u8;0x2000]) -> u8
或者
fn readByteFromMemory(internalRAM: &[u8;0x2000]) -> u8
我能找到唯一与这个主题相关的文章是这篇文章:http://words.steveklabnik.com/pointers-in-rust-a-guide,其中写道:
But don’t reach for that pointer until you must! Make sure that the
struct is large enough by performing some tests before you add in the
complexity of pointers.
我对这两个选项进行了基准测试,无论优化器开启还是关闭,传递指针的方式都比预期要快得多。
有趣的是,在优化器关闭的情况下,按值传递的速度略微更快,如下所示:
➜ rustTest$ rustc --test -O passByTest.rs
➜ rustTest$ ./passByTest --bench
running 2 tests
test ptrBench ... bench: 1 ns/iter (+/- 0)
test valueBench ... bench: 221 ns/iter (+/- 2)
test result: ok. 0 passed; 0 failed; 0 ignored; 2 measured
➜ rustTest$ rustc --test passByTest.rs
➜ rustTest$ ./passByTest --bench
running 2 tests
test ptrBench ... bench: 13 ns/iter (+/- 3)
test valueBench ... bench: 152 ns/iter (+/- 1)
我的问题是:在字节阈值上,通过传递引用比传递值更有意义?
llvm.lifetime.end
放置过于保守存在问题)。 - user395760&[u8]
而不是&[u8; 0x2000]
。 - Vladimir Matveev[u8; 0x2000]
是按值逻辑传递的。这意味着你可能会修改它。所以它必须进行预防性复制。&[u8; 0x2000]
明确告诉它,你绝对不会修改你传递的东西,因此它不需要进行复制。 - DK.