Page 1 of 1
refactor vs performance?
Posted: Mon Nov 01, 2010 11:23 pm
by s.dot
As I'm working on the latest pet project of mine I've been told of the advantages of refactoring code and implementing it (thanks @josh).
My question is does one still refactor if it costs performance?
For example, I'm working on a function to fix nested elements into the correct order. I can grab and collect the nested elements inside of the function that does the first regexp call.
If i refactor this, I would have to make another expensive call to preg_match_all()
Re: refactor vs performance?
Posted: Tue Nov 02, 2010 1:42 am
by Christopher
I think maybe you are misunderstanding what refactoring is. When you refactor, all you are doing is changing the code in a way such that there is no external effect. Typically that means that all tests continue to pass. The reasons you refactor code are varied -- performance is often one of those reasons. But the reason you refactor is outside the scope of refactoring process itself.
Your question is really whether you should make a specific code change that may affect performance. That is unrelated to whether you are refactoring when you make that change.
The answer to that question has more to do with where you are in the development process. If you have well designed and functional code, then refactoring at this point that makes performance worse would need to provide some important maintainability benefits.
On the other hand, if you are early in the development process then it is difficult to know what -- in the long term -- will help or hurt performance. So you should proceed to produce the best designed code you can. The problem with focusing too much on performance now is that it may prevent you from making some good design decision that will allow good performance down the road, but with clearer and more maintainable code.
Re: refactor vs performance?
Posted: Tue Nov 02, 2010 6:36 am
by josh
If it changes the performance its technically not refactoring. If performance is a specification you care about, you should have a test. Write a test that calls it 1,000x and asserts that it takes <1 second, just an example. Make sure it passes - then you can refactor to make sure that specification is still passing.
Also Christopher is right it goes on a case by case basis. If I'm adding 1ms to a bbcode parsing script, its no big deal if it makes the code readable. If however I'm writing something that is the bottleneck of the whole system, performance can then become a higher priority than readability.
Refactoring is not always about making the code more readable, it can also be about making it perform better, more modular, etc.. Sometimes a refactoring temporarily can make the code less readable and that's an ok thing to do (although should not be your goal)