Javascript performance issue with loop - javascript

We are having performance issues with that code.It works in loop with 150 times.
That code work for betting, matches have empty bet fields on screen.Then that code works for fill winner odds with looking and comparing scores.
In example, if match finished with 1-0 home team win, i must write "MS1" on screen.And for making that, i must get score info using jQuery attr selector.
In the weekends, there are a lot of matches and it is crashing or it works too slow :/
Have you any ideas to work faster?
OddEngine = function(odd)
{
$("#matchCode_" + odd.ID).html(odd.C);
$("#match_" + odd.ID).attr("code",odd.C);
var status = $("#match_" + odd.ID).attr("status");
if (status == 1)
return;
var htscore = $("#othomeTeamScore_"+odd.ID).html();
var atscore = $("#otawayTeamScore_"+odd.ID).html();
var iy_htscore = $("#homeTeamHalfScore_"+odd.ID).html();
var iy_atscore = $("#awayTeamHalfScore_"+odd.ID).html();
for (var i = 0; i < odd.Odds.length; i++) {
var bet = odd.Odds[i];
var winnerMsOdd = 'F.X';
var winnerMsTitle = 'X';
if (htscore > atscore)
{
winnerMsOdd = 'F.1';
winnerMsTitle = '1';
}
else if (htscore < atscore)
{
winnerMsOdd = 'F.2';
winnerMsTitle = '2';
}
$("#match_"+odd.ID+" [oddcode='MS']").html(bet[winnerMsOdd]);
$("#match_"+odd.ID+" [oddtag='MS']").fadeIn();
$("#match_"+odd.ID+" [oddtag='MS']").html(winnerMsTitle);
if (currentSportId != 3)
{
var winnerIyOdd = 'S.X';
var winnerIyTitle = 'X';
if (iy_htscore > iy_atscore)
{
winnerIyOdd = 'S.1';
winnerIyTitle = '1';
}
else if (iy_htscore < iy_atscore)
{
winnerIyOdd = 'S.2';
winnerIyTitle = '2';
}
if (bet[winnerIyOdd])
{
$("#match_"+odd.ID+" [oddcode='IY']").html(bet[winnerIyOdd]);
$("#match_"+odd.ID+" [oddtag='IY']").fadeIn();
$("#match_"+odd.ID+" [oddtag='IY']").html(winnerIyTitle);
}
}
if (currentSportId == 1)
{
var winnerAuOdd = 'UNDER';
if (parseInt(htscore) + parseInt(atscore) > 2.5)
{
winnerAuOdd = 'OVER';
}
if (bet[winnerAuOdd])
{
$("#match_"+odd.ID+" [oddcode='AU']").html(bet[winnerAuOdd]);
$("#match_"+odd.ID+" [oddtag='AU']").fadeIn();
$("#match_"+odd.ID+" [oddtag='AU']").html(winnerAuOdd == 'UNDER' ? 'ALT' : 'ÜST');
}
var winnerTGOdd = 'GS.01';
var winnerTGtitle = "0-1";
if (parseInt(htscore) + parseInt(atscore) > 1 && parseInt(htscore) + parseInt(atscore) < 4)
{
winnerTGOdd = 'GS.23';
winnerTGtitle = "2-3";
}
else if (parseInt(htscore) + parseInt(atscore) > 3 && parseInt(htscore) + parseInt(atscore) < 7)
{
winnerTGOdd = 'GS.46';
winnerTGtitle = "4-6";
}
else if (parseInt(htscore) + parseInt(atscore) >= 7)
{
winnerTGOdd = 'GS.7P';
winnerTGtitle = "7+";
}
if (bet[winnerTGOdd])
{
$("#match_"+odd.ID+" [oddcode='TG']").html(bet[winnerTGOdd]);
$("#match_"+odd.ID+" [oddtag='TG']").fadeIn();
$("#match_"+odd.ID+" [oddtag='TG']").html(winnerTGtitle);
}
}
}
$("#msOdd_" + odd.ID).html(odd.C);
if (currentSportId == 1 || currentSportId == 2 || currentSportId == 7)
{
$("#htOdd_" + odd.ID).html(odd.Odds["F.1"]);
}
$("#uOdd_" + odd.ID).html(odd.C);
$("#tOdd_" + odd.ID).html(odd.C);
}

There's a lot of bad stuff in there:
Issues:
You are hammering away at the DOM repeatedly. This is unavoidable but you don't need to do as much as you are doing. A lot of the remaining points follow-up on how to avoid.
You're using attribute selectors. These are slow and don't have native methods to support in most non-XML scenarios so are going to force a lot more work out of the interpreter. Try as classes instead. You can have multiple classes and add/remove with jQuery addClass and removeClass functions without interfering with other classes. If you're supporting IE8, narrow down to nearest ID and use a tag selector with a class.
You're not caching any of your JQ selectors. $('#someId') does a bit of work (although is faster than just about anything else. If it's going to get re-used, assign to a var. Convention is: var $someId = $('#someId'); so you know it's a jqObject. This repeatedly: $('#someId <other stuff>) is probably slower than this: $someId.find(<otherstuff>) repeatedly. In your case, assuming odd.id is unique, you'd at least want: var $matchHtml = $("#matchCode_" + odd.ID) at the top of the loop.
You're doing a ton of UI stuff as you go. Consider building the collections you need and then handling it all at once after the loop. e.g. building two JQ objects for AU and TG (see the 'add' method) and then hitting them with the functionality they need once the loop is complete.
This is probably less of a big deal than the JQ stuff but you're using a lot of '.' operators unnecessarily. Every '.' does actually represent some work and in some cases actually represent getters like length which can do a fair bit more work since they have to count up the array elements. Here's the hyper-anal loop which also has the nice side-effect of being more concise:
var myOdds = odd.Odds,
i=myOdds.length;
//if order matters, this goes backwards. Easy fix: myOdds.reverse
while(i--){
thisOdds = myOdds[i];//if you're using thisOdds more than once
//do stuff here
}

You could the '#match'+odd.ID node and key all your node searches within the loop from this node. eg. matchOdd.find( '[oddcode="MS"]' ), this should improve the performance against querying the DOM.
As for improving performance in the loop you could consider making it async by delegating to setTimeout. Here is a link to a resource that explains how to approach this http://www.kryogenix.org/days/2009/07/03/not-blocking-the-ui-in-tight-javascript-loops

Related

Javascript - if-statement with multiple numeric conditions doesn't work

I'm trying to make a simple program in javascript+html. If exp exceeds within a certain range/exceeds a certain number, the level displayed goes up by 1. I've tried to make it show onload, but the level doesn't change no matter what happens to the exp staying at the highest one I've written code for so far.
Javascript:
var exp6 = localStorage.exp6;
var pexp6 = parseInt(exp6);
function char6() {
res.innerHTML = res6;
var lsps = pexp6;
localStorage.setItem("lsp", lsps);
return PrUpdate();
}
var lsp = localStorage.lps;
function PrUpdate() {
if (lsp <= 999) {
lvl.innerHTML = 1;
}
else if (lsp >= 1000 && lsp <= 1999) {
lvl.innerHTML = 2;
}
else if (lsp >= 2000 && lsp <= 2999) {
lvl.innerHTML = 3;
}
else if (lsp >= 3000 && lsp <= 3999) {
lvl.innerHTML = 4;
}
else if (lsp >= 4000 && lsp <= 4999) {
lvl.innerHTML = 5;
}
}
I've also included the setChar() function in the window.onload of the page. I've tried including the function itself in it as well, but whether I add it at the end of the setChar() or in the window.onload the problem stays the same. All other functions work fine, it's just this part that doesn't. I'm also trying to make it generic to fit other 'accounts' I'm trying to make to save myself time. But I just can't make it work.
Edit:
I've figured out why it didn't work, and it was cause I had my localStorage.lsp in the wrong place.
I'm trying to figure out now how to make it so I don't have to refresh the page to get it to appear.
[ Solved my issue :), if unclear by my edit above]
The way you are trying to access values from localstorage is incorrect. This is not valid: localstorage.exp6.
Instead try this: localstorage.getItem('exp6')
See the documentation of Web Storage API for more information

Handling events with new data before previous event has completed

This code takes two inputs: div, the div (actually a textbox) and target (a number). It'll then try and in/decrement the number in a pseudo-animated way. The problem is that I'm using jQuery sliders as one form of input, which can result in multiple calls before the first call finished. This isn't a problem unless the slider is quickly increased, and then decreased before the increase rollUp finishes, resulting in an eternal decrementing div. I can't figure out what's causing it. Thoughts?
function rollNum(div, target) {
var contentString = $(div).val();
content = parseInt(contentString.substring(1));
if(content === target)
return;
else if(div !== "#costMinusMSP" && div !== "#savingsWithMSP") {
var total = rollNumTotalCost(div, target);
rollNum("#costMinusMSP", total);
rollNum("#savingsWithMSP", total /*- somehow find the cost here*/)
}
if(isNaN(content))
content = 0;
var remainingChange = target - content;
if(remainingChange > 0)
loopUp();
else
loopDown();
function loopUp() {
var length = remainingChange.toString().length;
var incrementBy = 1;
//Find how far away we are from target
for(var i=0;i<length-1;i++)
incrementBy *= 10;
content += incrementBy;
remainingChange -= incrementBy;
$(div).val("$" + (content))
if(content === target)
return;
else if(content > target) {
$(div).val("$" + (target));
return;
}
setTimeout(loopUp, 60);
}
function loopDown() {
remainingChange = Math.abs(remainingChange);
var length = remainingChange.toString().length;
var decrementBy = 1;
//Find how far away we are from target
for(var i=0;i<length-1;i++)
decrementBy *= 10;
content -= decrementBy;
remainingChange -= decrementBy;
if(content < target) {
$(div).val("$" + (target));
return;
}
//This ensures we won't promise our clients negative values.
if(content <= 0) {
$(div).val("$0");
return;
}
$(div).val("$" + (content))
if(content === target)
return;
setTimeout(loopDown, 60);
}
}
Strangely enough, adjusting another slider (that modifies an unrelated div) fixes the eternal decrement.
Things I have tried:
-Creating a boolean "running" that the function sets to true, then false before it returns. If running was true, then the function would wait until it was false to continue executing. This killed the browser or achieved maximum stack.
SomeKittens of years ago: You've learned a lot since you asked this, particularly about managing state & multiple events (not to mention how to properly ask a StackOverflow question). A simple answer would be something like this:
var rolling = false;
function rollNum(div, target) {
if (rolling) { return; }
rolling = true;
// Set rolling to false when done
}
That's all well and good but it ignores any events that are fired while we're rolling. The above won't adjust to changes on the slider made after the first adjustment, but before the numbers have finished rolling. Now, I (we?) would use Angular ($scope.$watch would come in handy here) but that didn't exist when you were working on this. Instead of passing a target number, why don't we check against the live value on the slider? (Note the use of vanilla JS, it's much faster).
var rollNum = function(textarea) {
var content = parseInt(textarea.value.substring(1), 10)
, target = parseInt(document.getElementById('sliderId').value, 10);
if (content === target) {
return;
}
// Roll up/down logic
setTimeout(function() { rollNum(textarea); }, 60);
};
A few other misc changes:
Use brackets after if statements. Waaaay easier to debug
Don't forget the radix param in parseInt
Unfortunately, you didn't think to include a JSFiddle, so I can't provide a live demonstration.

A jQuery 'if' condition to check multiple values

In the code below, is there a better way to check the condition using jQuery?
if(($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value'))
Unless there are other concerns, like if you will reuse the #test1, ... fields for more processing, yours should be good.
If you will fetch any of the values again to do something I would recommend storing the $('#test1') result in a variable so that you do not need to requery the dom.
Ex:
var t1 = $('#test1');
if((t1.val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value')) {
t1.val('Set new value');
}
This also improves readability of the row ;)
var values = ['first_value', 'second_value', 'third_value', 'fourth_value'];
$('#test1, #test2, #test3, #test4').each(function(index, el) {
if($.inArray(this.value, values)) {
// do some job;
return false; // or break;
}
});
var c=0, b='#test', a=['first_value','second_value','third_value','fourth_value'];
for(var i=0; i<4; i++)
if($(b+i).val() == a[i])
c=1;
if (c) //Do stuff here
This will decrease your code size by 25 bytes;-)
Demo: just another idea is at http://jsfiddle.net/h3qJB/. Please let me know how it goes.
You can also do chaining like:
$('#test1, #test2, #test3, #test4').each(function(){ //...use this.value here });
It might be that De Morgan's laws gives you an idea of how to make the logic a bit more compact (although I am not sure what is the specific case or is it as simple as comparing values).
Code
var boolean1 = (($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value'))
var boolean2 = (($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value'))
if (boolean1 && boolean2)
alert("bingo");
else
alert("buzzinga");

Strip unwanted tag in a string (no JQuery)

I have a string that contains the following:
<span>A</span>BC<span id="blabla">D</span>EF
i want to be able to use the JavaScript replace function with regx expression to only remove the spans that do not have an id. So that the result would look like
ABC<span id="blabla">D</span>EF
I am really not interested in using jQuery. I would rather use pure JavaScript to solve the problem. I have the following but it does not seem to properly work
myText.replace(/(<([^>]+)>)/ig,"");
Any help would be appreciated!
Use the DOM, not a regexp.
var input = '<span>A</span>BC<span id="blabla">D</span>EF',
output,
tempElt = document.createElement('span');
tempElt.innerHTML = input;
// http://www.quirksmode.org/dom/w3c_html.html#t03
if (tempElt.innerText) output = tempElt.innerText;
else output = tempElt.textContent;
console.log(output); // "ABCDEF"
Demo: http://jsfiddle.net/mattball/Ctrkf/
"It is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail."
Something like this will do the job, but it doesn't use a regular expression (but it doesn't use jQuery either, so one out of two ain't bad).
var s = '<span>A</span>BC<span id="blabla">D</span>EF';
function removeSpans(s) {
var a = document.createElement('div');
var b = a.cloneNode(true);
a.innerHTML = s;
var node;
while (a.firstChild) {
node = a.removeChild(a.firstChild);
if (node.tagName &&
node.tagName.toLowerCase() == 'span' &&
node.id == '') {
b.appendChild(document.createTextNode(getText(node)));
} else {
b.appendChild(node);
}
}
return b.innerHTML;
}
alert(removeSpans(s));
It's not particularly robust (actually it works better than I thought it would) and will likely fail in cases slightly different to the test case. But it shows the strategy.
Here's another version, pretty similar though:
function removeSpans2(s) {
var a = document.createElement('div');
a.innerHTML = s;
var node, next = a.firstChild;
while (node = next) {
next = next.nextSibling
if (node.tagName && node.tagName.toLowerCase() == 'span' && !node.id) {
a.replaceChild(document.createTextNode(node.textContent || node.innerText), node);
}
}
return a.innerHTML;
}

More efficient comparison of numbers

I have an array which is part of a small JS game I am working on I need to check (as often as reasonable) that each of the elements in the array haven't left the "stage" or "playground", so I can remove them and save the script load
I have coded the below and was wondering if anyone knew a faster/more efficient way to calculate this. This is run every 50ms (it deals with the movement).
Where bots[i][1] is movement in X and bots[i][2] is movement in Y (mutually exclusive).
for (var i in bots) {
var left = parseInt($("#" + i).css("left"));
var top = parseInt($("#" + i).css("top"));
var nextleft = left + bots[i][1];
var nexttop = top + bots[i][2];
if(bots[i][1]>0&&nextleft>=PLAYGROUND_WIDTH) { remove_bot(i); }
else if(bots[i][1]<0&&nextleft<=-GRID_SIZE) { remove_bot(i); }
else if(bots[i][2]>0&&nexttop>=PLAYGROUND_HEIGHT) { remove_bot(i); }
else if(bots[i][2]<0&&nexttop<=-GRID_SIZE) { remove_bot(i); }
else {
//alert(nextleft + ":" + nexttop);
$("#" + i).css("left", ""+(nextleft)+"px");
$("#" + i).css("top", ""+(nexttop)+"px");
}
}
On a similar note the remove_bot(i); function is as below, is this correct (I can't splice as it changes all the ID's of the elements in the array.
function remove_bot(i) {
$("#" + i).remove();
bots[i] = false;
}
Many thanks for any advice given!
Cache $("#" + i) in a variable; each time you do this, a new jQuery object is being created.
var self = $('#' + i);
var left = parseInt(self.css("left"));
var top = parseInt(self.css("top"));
Cache bots[i] in a variable:
var current = bots[i];
var nextleft = left + current[1];
var nexttop = top + current[2];
Store (cache) the jQuery object of the DOM element within the bot representation. At the moment it's been created every 50ms.
What I mean by this is that for every iteration of the loop, you're doing $('#' + i). Every time you call this, jQuery is building a jQuery object of the DOM element. This is far from trivial compared to other aspects of JS. DOM traversal/ manipulation is by far the slowest area of JavaScript.
As the result of $('#' + i) never changes for each bot, why not store the result within the bot? This way $('#' + i) gets executed once, instead of every 50ms.
In my example below, I've stored this reference in the element attribute of my Bot objects, but you can add it your bot (i.e in bots[i][3])
Store (cache) the position of the DOM element representing the bot within the bot representation, so the CSS position doesn't have to be calculated all the time.
On a side note, for (.. in ..) should be strictly used for iterating over objects, not arrays. Arrays should be iterated over using for (..;..;..)
Variables are extremely cheap in JavaScript; abuse them.
Here's an implementation I'd choose, which incorporates the suggestions I've made:
function Bot (x, y, movementX, movementY, playground) {
this.x = x;
this.y = y;
this.element = $('<div class="bot"/>').appendTo(playground);
this.movementX = movementX;
this.movementY = movementY;
};
Bot.prototype.update = function () {
this.x += this.movementX,
this.y += this.movementY;
if (this.movementX > 0 && this.x >= PLAYGROUP_WIDTH ||
this.movementX < 0 && this.x <= -GRID_SIZE ||
this.movementY > 0 && this.y >= PLAYGROUND_HEIGHT ||
this.movementY < 0 && this.y <= -GRIDSIZE) {
this.remove();
} else {
this.element.css({
left: this.x,
right: this.y
});
};
};
Bot.prototype.remove = function () {
this.element.remove();
// other stuff?
};
var playground = $('#playground');
var bots = [new Bot(0, 0, 1, 1, playground), new Bot(0, 0, 5, -5, playground), new Bot(10, 10, 10, -10, playground)];
setInterval(function () {
var i = bots.length;
while (i--) {
bots[i].update();
};
}, 50);
You're using parseInt. As far as I know, a bitwise OR 0 is faster than parseInt. So you could write
var left = $("#" + i).css("left") | 0;
instead.
Furthermore, I wouldn't make use of jQuery functions to obtain values like these every 50 ms, as there's always a bit more overhead when using those (the $ function has to parse its arguments, etc.). Just use native JavaScript functions to optimize these lines. Moreover, with your code, the element with id i has to be retrieved several times. Store those elements in a variable:
var item = document.getElementById(i);
var iStyle = item.style;
var left = iStyle.left;
…
(Please note that I'm not a jQuery expert, so I'm not 100% sure this does the same.)
Moreover, decrementing while loops are faster than for loops (reference). If there's no problem with looping through the elements in reverse order, you could rewrite your code to
var i = bots.length;
while (i--) {
…
}
Use offset() or position() depending on if you need coordinates relative to the document or the parent. position() is most likely faster since browsers are efficient at finding offsets relative to the parent. There's no need for parsing the CSS. You also don't need the left and top variables since you only use them once. It may not be as readable but you're going for efficiency:
var left = $("#" + i).position().left + bots[i][1];
var top = $("#" + i).position().top + bots[i][2];
Take a look here for a great comparison of different looping techniques in javascript.
Using for...in has poor performance and isn't recommended on arrays. An alternative to looping backwards and still using a for loop is to cache the length so you don't look it up with each iteration. Something like this:
for(var i, len = bots.length; i < len; i++) { ... }
But there are MANY different ways, as shown in the link above and you might want to test several with your actual application to see what works best in your case.

Categories