This is probably a common pattern in coding, though I am not knowledgeable enough to recognize it or use the correct terminology (I would've googled it then).
When you are creating an object that will invoke a method in a loop, but the content of the loop can change according to a certain set of conditions, do you do (pseudo-code):method _method($condition){
switch($condition){}
}
or
method init($condition){
switch($condition){
case 1:
this._method = function开发者_运维问答(){};break;
case 2:
this._method = function(){};break;
....
}
}
I prefer version 1 as it is more maintainable, but I feel version 2 is lighter. Am I correct?
I realize the answer can differ quite a lot depending on the use case, so here is mine: I have a javascript slider, implemented as a jQuery plugin. depending on options, when the slider comes to the last frame, it either scrolls back to start, or seamlessly loops. Now, if it must seamlessly loop, then when each slide advance, I must set the element that has just disappeared on the left to be queued at the far right. Which means I have to detect when the element has disappeared from the view, and do a helluva of other checks for scrollLeft values and whatnot that I don't need to do if I am simply scrolling.
So how should I go about that?I'm sure you understand this, but it's worth repeating:
If it ain't broke, don't fix it.
You can almost never find a performance problem in non-toy software by just thinking about it.
When people learn how to solve performance problems (as, IMHO, I have), they are often asked what the secret is. The secret is simple - don't guess, do diagnose. Here's the method I use.
Everybody knows that, but they go ahead guessing anyway.
For one example, review the answers to this question.
Your use case seems to be simple and doesn't need much computing time, though you should use the code which is more readable for you and easier to maintain. When using performance critical code you should keep the code within a loop as short/inexpensive as possible.
精彩评论