views:

155

answers:

3

I have this piece of JavaScript on my page and it loads the CPU considerably. Is there any way to optimize the code? ( I'm using jQuery, so jQuery solutions will be fine )

function Particle() {

            this.particleContainerWidth = $('#particle-container').width() - 100;
            this.particleContainerHeight = $('#particle-container').height() - 100;

            this.path = 'img/';
            this.images = ['particle1.png', 'particle2.png', 'particle3.png', 'particle4.png'];

        //  Randomly Pick a Particle Model
            this.image = this.images[randomInt(this.images.length)];
            this.file = this.path + this.image;

        //  Create a Particle DOM
            this.element = document.createElement('img');

            this.speed().newPoint().display().newPoint().fly();
        };

        //  Generate Random Speed
        Particle.prototype.speed = function() {
            this.duration = (randomInt(10) + 5) * 1100;
            return this;
        };

        //  Generate a Random Position                               
        Particle.prototype.newPoint = function() {
            this.pointX = randomInt(this.particleContainerWidth);
            this.pointY = randomInt(this.particleContainerHeight);

            return this;
        };

        //  Display the Particle
        Particle.prototype.display = function() {
            $(this.element)
                .attr('src', this.file)
                .css('position', 'absolute')
                .css('top', this.pointY)
                .css('left', this.pointX);
            $('#particle-container').append(this.element);

            return this;
        };

        //  Animate Particle Movements
        Particle.prototype.fly = function() {
            var self = this;
            $(this.element).animate({
                "top": this.pointY,
                "left": this.pointX
            }, this.duration, 'linear', function(){
                self.speed().newPoint().fly();
            });
        };

        function randomInt(max) {
        //  Generate a random integer (0 <= randomInt < max)
            return Math.floor(Math.random() * max);
        }

       $(function(){

            $('body').append('<div id="particle-container"></div>');

            var total = 8;
            var particles = [];

            for (i = 0; i < total; i++){
                particles[i] = new Particle();
            }
        }); 
+1  A: 

You cannot make JavaScript consume less of your CPU. That is governed by the priority of the executing application in the OS kernel. The best you can hope for is to reduce execution time.

To improve your execution efficiency limit your usage of prototype and stop assigning values to properties. This method of coding has become popular because it is extremely clean and easy to read, but it horribly backwards to execute.

If you are capable of coding using only variables for assignment, if statements for decisions, and for loops for looping your code execution will be far faster. That will require you to write more code, however, and it will not be so pretty.

To improve output performance write all output segments each into an index of an array and use only a single join method when all output is created and a single innerHTML method to output this text to the page. This will reduce output execution by up to 4 times.

+1  A: 

Have you thought about implementing this with a <canvas> version? It won't work in IE directly, of course, and off-hand I'm not sure whether it'd be faster or slower. You could also try it with Processing.

Pointy
+1  A: 

This would need a lot of changing and rewriting, but You can create a new easing function for jquery and post it to animate. Then every particle You have would just be once issued with animate() with Your easing function and the function has to be based on those:

  • random
  • current time (new Date()) modulo some number
  • a singleton holding individual directions

ideas:

Assuming You don't want to change Your code You can try setting the particle to fly with some random timeout when first running fly(). It could change the way it's all executed. No idea if it helps or makes it slower though ;)

Second thing is quality. jquery animate does it too smoothly. You can move Your particles instead of animating and just chande the distance to lower and increase speed and use setTimeout to make it move the same pace as now.

naugtur