Efficient Twitch Stream List Call

Hey all, I’ve created the following call function to get a list of the current streams and it works, but I know that my javascript can be more efficient. I pull the info from the JSON file and create variables for the streamer’s name, game, viewers, and preview image. I then append those onto my main wrapper in the html page. Any suggestions is appreciated.

Thanks,

  $.getJSON("https://api.twitch.tv/kraken/streams/?callback=?").done(function(data) {

		$.each(data.streams, function() {
			$.each(this, function(name, value) {
				if(name === "game") {
					$gname = value;
				}
				
				if (name === "channel") {
					$dname = value.display_name;
				}
				
				if(name === "viewers") {
					$viewers = value;
				}
				
				if(name === "preview") {
					$img = value.large;
				}
				
			});
			
			var $title = "<span class='streamer-name'>" + $dname + "</span>";
			var $game = "<span class='game'>" + $gname + "</span>";
			var $pic = "<img src=" + $img + "/>";
			var $view = "<span class='streamer-viewers'>" + $viewers + "</span>";
			
                             var $tile = "<div class='img-responsive thumbnail col-sm-3'>" + $title + "" + $game + "" + $pic + 
"" + $view + "</div>";
			$('#main-tiles').append($tile);
				
		});
	});

Boosting performance are rarely worth the effort. You can get tiny improvements by not testing each name more than necessary:

if(name === "game") {
	$gname = value;
} else if (name === "channel") {
	$dname = value.display_name;
} else if(name === "viewers") {
	$viewers = value;
} else if(name === "preview") {
	$img = value.large;
}

And an even more microscopic boost by creating nodes programmatically through createElement and appendChild, according to this grossly simplified jsPerf: http://jsperf.com/jquery-vs-createelement

I can’t stress enough that unless you are making real-time applications where performance is everything, spending time increasing efficiency is a very inefficient use of your time.

You also don’t need to include a callback in the API URL since Kraken supports CORS.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.