Search code examples
javascriptcoding-stylecomputation-theory

Is it more efficient to request value or to just automatically set it


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?


Solution

  • 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.