简体   繁体   中英

Using probability to minimizing conditional evaluations for speed-up

Consider a scenario when you have integers in range [1, BIG_NUMBER]; If the number is divisible by 3, print foo ; If the number is divisible by 5, print bar ; Divisible by both 3 and 5, print foobar ;

One way to do it is

// READABILITY IS GOOD
const func1 = length => {
    for (let i = 0; i <= length; i++) {
        let output = i;
        if (i % 3 === 0) output = 'foo';
        if (i % 5 === 0) output = 'bar';
        if (i % 3 === 0 && i % 5 === 0) output = 'foobar';
        console.log(output);
    }
};

Now if we think along the lines of probability, probability to be divisible by 3: p(3) = 1/3,

similarly divisible by 5: p(5) = 1/5

and divisible by both p(3 && 5) = 1/15

divisible by either one of the two p(3 || 5) = p(3) + p(5) - p(3 && 5)

Now instead of the above snipped, I write nested if statements:

const func3 = length => {
    for (let i = 0; i <= length; i++) {
        if (i % 3 === 0) {
            if (i % 5 === 0) {
                console.log('foobar');
            } else {
                console.log('foo');
            }
        } else if (i % 5 === 0) {
            console.log('bar');
        } else {
            console.log(i);
        }
    }
};

Approach is to put most probable if statement first, and least probable if statement last, which should minimize conditional evaluations.

Will it attain speed up? Still checking at my end, and will post my findings also . But I am just wondering does anyone think along these lines. Is it even used in practice ? or just a waste of time, that also screws up a readable code for a minimal gain

Don't do either of these arrangements: you do have to test for both conditions in some form or another. Instead, use a progressive build of the output:

noise == ""
if (i % 3 === 0) noise += "foo"
if (i % 5 === 0) noise += "bar"
if (noise == "") noise = i
console.log(noise)

Simple, readable, and reasonably quick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM