4 ms·
In performance sensitive code without getting into unsafe you would write this function like this: https://godbolt.org/z/PTsnTMq7M https://godbolt.org/z/PTsnTMq
by newpavlov 5y ago
In performance sensitive code without getting into unsafe you would write this function like this: https://godbolt.org/z/PTsnTMq7M https://godbolt.org/z/PTsnTMq7M
Effectively it results in the same assembly as for the completely unsafe C++ code, apart from the 3 instructions which test slice length. During normal operation they are trivial for branch predictor, so their impact will be negligible in the most cases (but not always, e.g. if this function is part of a hot loop, but then inlining should come to the rescue) and in many cases this check will be removed if compiler is able to prove that the condition is always true. So in the worst case scenario you will lose several cycles on the test instructions and the panic code may slightly increase pressure on I-cache, which I think is a good price to pay for the safety.