by tsimionescu · 2y ago · 0 comments
I tried it, code: https://pastebin.com/cA8YkE8R
Result:
process1: 2s 251.327833ms
process2: 1s 537.721625mshttps://play.rust-lang.org/?version=stable&mode=release&edit...
(I'd recommend running it on your own machine as the rust playground limits memory and will likely kill this program)
Output from my machine:
$ cargo run --release
Finished `release` profile [optimized] target(s) in 0.05s
Running `target/release/iterator`
Process 1 returned 18270843109002848788 and took 64.58175ms
Process 2 returned 18270843109002848788 and took 308.969083msA proper comparison could be:
# Case 1.
for n in range(len(data)):
data[n] = transform1(data[n])
data[n] = transform2(data[n])
# Case 2.
for n in range(len(data)):
data[n] = transform1(data[n])
for n in range(len(data)):
data[n] = transform2(data[n]) function process3(input) {
return input
.flatMap((n) => (n % 2 === 0 ? n * 2 : []))
.reduce((a, b) => a + b, 0)
} function processfor(input){
let sum = 0
for (let i = 0; i < input.length; i++){
if (input[i] % 2 !== 0){ continue }
sum += input[i] * 2
}
return sum
}
https://jsfiddle.net/gaby_de_wilde/y7a39r15/5/Of course, if you want the most performant solution an imperative for loop is faster (which is what I said in my last comment).
It's only for small arrays actually that the cost of the loop infra and the extra cache miss per loop matters.
for i := range arr {
foo1(arr[i])
...
foo10(arr[i])
}
Vs for i := range arr {
foo1(arr[i])
}
...
for i := range arr {
foo10(arr[i])
}