HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Generating a random number of progress bars

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomnumberprogressgeneratingbars

Problem

I have this JSFiddle that generates a random number of progress bars then assigns a random number and percent to them.

I am wondering if you know how to better optimize this code to have better run-time.



/Creates a random amount of bars/

function runBars() {
var start = new Date().getTime();
/Sets the maximuim amount of bars, 10 if NaN or less than 1/
var max_bars = parseInt($('#max_bars').val());
if (isNaN(max_bars) || max_bars Number ' + (i + 1) + '');
$('#bars-container').append(element);
}
var end = new Date().getTime();
var time = end - start;
$('#bar_time').text(time);
$('#bar_amount').text(bars);
/Populates bars with percents/
runPercent();
}

/Random int with max/
function getRandom(max) {
return Math.floor((Math.random() * max) + 1);
}

/Gets percent based on maxium number, making the percent scale /
function getPercent(x, total, biggest) {
return Math.floor(x / biggest * 100) + '%';
}

/Populates percent in each progress bar/
function runPercent() {
var start = new Date().getTime();
var length = $('.progress-bar').size();
var data = [];
var total = 0;
var biggest = 0;
/pushes random ints to array/
for (var i = 0; i
.float {
position:fixed;
right:0px;
text-align:right;
}


Randomize %
Randomize Bars



Result:

Amount of Bars:

In Miliseconds:

Bar Time:
Percent Time:

`

Solution


  1. Native methods will perform better than jQuery equivalents



Replacing jQuery calls with the native JavaScript equivalents where possible will improve performance. This will also increase the verbosity of your code, which may be undesirable, although arguably it can make the code more readable/less ambiguous.

Examples:

-
Use document.getElementById('ID') instead of $('#ID') when retrieving a single element by its ID

  • use document.querySelector('.className') instead of $('.className') when retrieving a single element by a CSS selector



  • Use document.querySelectorAll('.className') instead of $('.className') when retrieving an array of elements by a CSS selector



  • Use Element.innerHTML to update the text/html inside an element instead of using $(.cssSelector).html() or $(.cssSelector).text()



  • If you're only appending HTML to an element, use the more efficient Element.insertAdjacentHTML('beforeend',YourHTML) instead of modifying Element.innerHTML



  1. Don't query the DOM for elements any more than you need to



In some cases your code selects an element multiple times. You can improve performance by selecting it once and saving it to a variable, then referencing that variable instead of selecting it again. Otherwise the JavaScript is forced to crawl the DOM multiple times to retrieve the same element.

Examples:

  • In the runBars() method, $('#bars-container') is called once to clear its HTML content, then again several times (once for every bar) to append more HTML to it. This is causing performance to degrade steeply as the number of bars increases.



  • Similarly, in the runPercent() method, the array of progress bars is selected via $('.progress-bar') once to get its length, then selected a second time to set the width and text of each progress bar.



  1. Include a Radix parameter when calling parseInt()



This one is more of a minor nitpick: when calling parseInt() you should make it a habit to include a radix parameter indicating the base of the number in the string.

Otherwise the browser will do its best to pick the right base system based on the string value... strings that start with '0x' will be considered hexadecimal, while strings that start with '0' will be considered octal, and any other strings will be considered decimals.

Making a habit of passing 10 explicitly as your radix parameter will not only save the browser the tiny bit of effort it expends on checking for a string prefix, but it will save you from headaches if you ever find yourself parsing a string with a zero preceding a decimal number.

Example Code

Check out the performance of the code below, which has no jQuery dependencies except for the progress bar CSS:



/Creates a random amount of bars/

function runBars() {
var start = new Date().getTime();
/Sets the maximuim amount of bars, 10 if NaN or less than 1/
var max_bars = parseInt(document.getElementById('max_bars').value, 10);
if (isNaN(max_bars) || max_bars Number ' + (i + 1) + '');
}
var end = new Date().getTime();
var time = end - start;
document.getElementById('bar_time').innerHTML = time;
document.getElementById('bar_amount').innerHTML = bars;
/Populates bars with percents/
runPercent();
}

/Random int with max/
function getRandom(max) {
return Math.floor((Math.random() * max) + 1);
}

/Gets percent based on maxium number, making the percent scale /
function getPercent(x, total, biggest) {
return Math.floor(x / biggest * 100) + '%';
}

/Populates percent in each progress bar/
function runPercent() {
var start = new Date().getTime();
var progressBars = document.querySelectorAll(".progress-bar");
var data = [];
var total = 0;
var biggest = 0;
/pushes random ints to array/
for (var i = 0; i
.float {
position: fixed;
right: 0px;
text-align: right;
}


Randomize %
Randomize Bars



Result:

Amount of Bars:

In Miliseconds:

Bar Time:
Percent Time:

`

Context

StackExchange Code Review Q#82576, answer score: 2

Revisions (0)

No revisions yet.