gpt4 book ai didi

javascript - 如何优化这个js(现在页面打开时CPU超过40%)

转载 作者:行者123 更新时间:2023-11-30 13:40:52 25 4
gpt4 key购买 nike

我的页面上有这段 JavaScript,它会显着占用 CPU。有什么办法可以优化代码吗? (我正在使用 jQuery,所以 jQuery 解决方案会很好)

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();
}
});

最佳答案

您无法让 JavaScript 消耗更少的 CPU。这由操作系统内核中正在执行的应用程序的优先级决定。您所能期望的最好结果就是减少执行时间。

为了提高执行效率,请限制原型(prototype)的使用并停止为属性赋值。这种编码方法之所以流行,是因为它非常简洁易读,但执行起来却非常倒退。

如果您能够仅使用用于赋值的变量、用于决策的 if 语句和用于循环的 for 循环进行编码,您的代码执行速度将会快得多。然而,这将需要您编写更多代码,而且不会那么漂亮。

为了提高输出性能,将所有输出段分别写入数组的索引中,并在创建所有输出时仅使用一个连接方法,并使用一个 innerHTML 方法将此文本输出到页面。这会将输出执行减少多达 4 倍。

关于javascript - 如何优化这个js(现在页面打开时CPU超过40%),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2347847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com