Tutorial :Is there a performance difference between these two pieces of code?


Is there a performance difference between these two pieces of code? My gut feeling is that the second option is slower, as the Cell object has to be constructed each time, but I like the idea of returning a Cell.

Option One:

//Call to method  initiTextDefaultCell(borders);  iTextTable.setDefaultCell(iTextDefaultCell);  //Other code...    private void initiTextDefaultCell(boolean borders) {    if (!borders)      iTextDefaultCell.setBorder(Rectangle.NO_BORDER);    else       iTextDefaultCell.setBorder(Rectangle.BOX);  }  

Option Two:

//Call to method  iTextTable.setDefaultCell(initiTextDefaultCell(borders));  //Other code...    private Cell initiTextDefaultCell(boolean borders) {    Cell iTextDefaultCell = new Cell();    if (!borders)      iTextDefaultCell.setBorder(Rectangle.NO_BORDER);    else       iTextDefaultCell.setBorder(Rectangle.BOX);    return iTextDefaultCell;  }  



As you've said option two will be slower due to the allocation of a new object.

This looks like a clarity-of-code vs. performance decision. I personally think option two is clearer and that the performance impact would be negligible.

However without knowing what iTextTable is it's hard to say for certain which to use. If initiTextDefaultCell is called once when the table is instantiated then I'd go with option two, however if the number of times initiTextDefaultCell is called depends on the size of the table then option one would be better (assuming that the default cell was instantiated as part of the instantiation of iTextTable).


Write a test program and see for yourself.


hmmm... which is slower, 10ms, or 1ms?

Option 2 will be slower than Option 1, yes, but even though the difference might be a factor of 10, even that "high" factor, when the slow version is sufficiently fastwill not be noticed by a human (The numbers used are just given as examples).

The first rule of performance is, only optimise when you have to. The second rule of performance, is a well designed system will typically have good performance, and be easier to optimise when required.

Option 2 is a lot more readable, and a better design. That is because the method creates the Cell configures it as well.


The second one is (probably) slower (but see Mnementh's comment). It's doing everything the first one is doing and more. But that doesn't mean you shouldn't use it if you think it's the better design (and I tend to agree). As Lou said, this probably isn't your bottleneck. If you need to know for sure, test.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »