Pergunta

So I am writing code in javascript that I am trying to make the code as efficient as possible because it will be running through a but load of data. My questions which is more efficient:

1.

foreach MyObjects{
    if(MyObject.getBoolean() == false){
        MyObject.setBoolean(true);
    }
}

2.

foreach MyObjects{
    MyObject.setBoolean(true);
}

I know my foreach is not real but I am asking which is better when running the statement many thousands of times?

Foi útil?

Solução

I can see why you would think that the first might be okay because there is a 'filtering' element. But the iterator still has to iterate over all the values whether they are false or not, so just explicitly telling them to be true wields the same results but with one less function call.

So the latter.

Edit:

As Ken suggests, it depends how expensive the different setBoolean and getBoolean methods are. If setBoolean does more than just set a value to true, then the first could possibly be quicker. But it's hard to imagine they do anything other than what their method names suggest.

Outras dicas

I coud be wrong, but it seems like the second option required less steps:

foreach MyObjects{
    MyObject.setBoolean(true);
}

In the first option you are checking the Boolean for each and every value and then for those that are false, you are setting to true. (1 operation guaranteed (get), with the possibility of second (set)). In the second method you are also finding every object, but skipping the check and simply setting (1 operation only). Therefore, although there probably isn't a significant difference in the runtime, the second one is more efficient.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top