SitePoint Sponsor

# Thread: Optimization

1. ## Optimization

Hey everyone is there a way in which I could optimize my code with
just one for loop (see code below). I've come across this issue a few
times now and haven't found a solution as yet.. As you can see from
the code below I'm reusing the same loop throughout three functions, I
basically see this as a waste. Is there a more efficient way where I
could use the for loop just the once.

var overStates = [
['0','imgs/membersHome/set01Over.jpg', 'imgs/membersHome/
set01Up.jpg'],
['1','imgs/membersHome/set02Over.jpg', 'imgs/membersHome/
set02Up.jpg'],
['2','imgs/membersHome/set03Over.jpg', 'imgs/membersHome/
set03Up.jpg'],
];

function imgState(event){
var target = getTarget(event, 'a'), i;
for(i = 0; i < overStates.length; i++){
amyObj.removeImgStates(i, 2);
if(overStates[i][0] == target.firstChild.name){
target.firstChild.src = overStates[i][1];
}
}
}

function overState(event){
var target = getTarget(event, 'a'), i;
for(i = 0; i < overStates.length; i++){
if(overStates[i][0] == target.firstChild.name){
target.firstChild.src = overStates[i][1];
}
}
}

function outState(event){
var target = getTarget(event, 'a'), i;
for(i = 0; i < overStates.length; i++){
if(overStates[i][0] == target.firstChild.name)
{
target.firstChild.src = overStates[i][2];
}
}

}

Cheers!

DoomedLung

2. I wouldn't worry about looping 3 times over 3 items. Even if you managed to combine them into one function, it would only save you 6 loop iterations - not exactly a big performance saving. Sometimes code simplicity/modularity should take priority over small performance increases.

3. Really? It just seemed to be wasteful. But if not, then why not eh!

Cheers dude thanks for your comment, much appreciated

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•