好的,所以我做了一个喊话框,我已经使用了一段时间,但是最近我注意到它因为对脚本的太多调用而消耗了 cpu 使用率,我想知道我怎么能去修复它的性能。
这是喊话框的 js 脚本。
var current_shouts = 0;
function $shoutid(eleid) {
return document.getElementById(eleid);
}
function urlencode(u) {
u = u.toString();
var matches = u.match(/[\x90-\xFF]/g);
if (matches) {
for (var mid = 0; mid < matches.length; mid++) {
var char_code = matches[mid].charCodeAt(0);
u = u.replace(matches[mid], '%u00' + (char_code & 0xFF).toString(16).toUpperCase());
}
}
return escape(u).replace(/\+/g, "%2B");
}
function shouts() {
clearTimeout(getshout);
var xmlHttp = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("GET", "shoutbox/shouts.php?i=" + Math.random());
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (parseInt(this.responseText) > current_shouts) {
getshouts();
current_shouts = parseInt(this.responseText);
}
getshout = setTimeout("shouts()", 1000);
}
}
xmlHttp.send(null);
}
function getshouts() {
var xmlHttp = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("GET", "shoutbox/getshouts.php?i=" + Math.random());
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4) $shoutid("shoutbox").innerHTML = this.responseText;
$shoutid("shoutbox").scrollTop = $shoutid("shoutbox").scrollHeight;
}
xmlHttp.send(null);
}
function push_shout() {
shout();
return false;
}
function shout() {
var xmlHttp = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("POST", "shoutbox/shout.php");
var data = "user=" + urlencode($shoutid("user").value) + "&" + "shout=" + urlencode($shoutid("shout").value);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", data.length);
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (!this.responseText) $shoutid("shout").value = "";
else {
alert(this.responseText);
}
getshouts();
}
}
xmlHttp.send(data);
return true;
}
var getshout = setTimeout("shouts()", 1000);
当谈到 js 时,我并不是最聪明的蜡笔,所以我不确定如何解决这个问题。调用shouts.php
是真正消耗我的 CPU 的东西。
这是脚本shouts.php
<?php
$db = new mysqli('localhost', 'username', 'pass', 'database');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$stmt = $db->query("SELECT COUNT(id) FROM shout");
while ($shout = $stmt->fetch_assoc()) {
echo implode($shout);
}
session_write_close();
?>
我阅读了会话锁定问题,所以我添加了,session_write_close();
但这似乎对我的问题没有帮助。
任何提示将非常感谢!