Earlier quoted context omitted.
> 126msec for 100k cycles. Or to put it another way: 1,200 nanoseconds. That's about 3,000-5,000 instructions on a modern CPU. Believe it or not, that's actually pretty bad . After jumping through some hoops to ensure that rustc doesn't just compile the whole thing down to a constant, I benchmarked my version as taking 15-20 nanoseconds per iteration. About 45-80 instructions! I actually couldn't quite believe it mys…
I'm not sure getting the wrong answer fast is something to be proud of. Your rust code has a bug in it, is longer, and you spent more time on it.
Thinking about it, this version boils down the logic to its barest essence:
fn test(input: &mut [&str]) {
let mut was_select = false;
for i in input.iter_mut() {
if was_select && *i == "*" { *i = "_"; was_select = false; }
else { was_select = *i == "select"; }
}
}
It runs in 5.5 nanoseconds per iteration, which is just absurdly fast. That's about 200x faster than your K version!What I like about this Rust version is that it reflects the approach that for a computer processor is optimal, yet it is high-level and readable. I could convert that "test" function easily enough to a generic "replace" function similar to a string search & replace, but one that can operate on any mutable iterator with the maximum possible efficiency, not just arrays.
Then, your K code that requires "careful reading" to slowly tease apart the meaning could be converted to a form that is practically prose:
let mut input = ["select", "*", "bar", "potato"];
replace( &mut input, &["select", "*"], &["select", "_"] );*