I developed a chat with php/ajax creating a recursive function, but I'm unsure about the performance and quality of the logic used

huangapple go评论86阅读模式
英文:

I developed a chat with php/ajax creating a recursive function, but I'm unsure about the performance and quality of the logic used

问题

I'm developing a simple chat plugin, it's ready however I'm having some doubts about the performance. I'm afraid of getting heavy for the servers.

It is based on a recursive function, calling an ajax, bringing the data from the database and printing it on the screen.

window.addEventListener('load', function(){
    RenderChat()
});

const chatObjectScriptsToUrlParams = (obj) =>{
    let params = "";
    for (var key in obj) {
        if (params != "") {
            params += "&";
        }
        params += key + "=" + encodeURIComponent(obj[key]);
    }
    return params;
}

const RenderChat = () => {

    let divChat = document.getElementById('dv-chat');

    let params = {
        action: 'DvChat',
        nounce: DvChat_js.nounce,
        url: DvChat_js.dv_chat_ajax,
    };

    params = chatObjectScriptsToUrlParams(params);

    fetch(DvChat_js.url + '?' + params)
        .then((response) => {
            return response.text();
        })
        .then((html) => {
            divChat.innerHTML = html;
            console.log('HTML => ', html);
        })
        .catch( () => {

        })
        .finally(() => {
            RenderChat();
        });
}

As I said, it's a very simple way to do it, I would really like your help to know if this is really the best way, or if there are adjustments, something I can improve on this idea.

I've seen people using setInterval(); but I chose to use a recursive function to reduce the number of requests.

It's the first time I'm developing a chat, and I don't know if it's right to make so many requests the way I did, I ended up having serious doubts about the performance related to the infrastructure.

英文:

i'm developing a simple chat plugin, it's ready however i'm having some doubts about the performance. I'm afraid of getting heavy for the servers.

it is based on a recursive function, calling an ajax, bringing the data from the database and printing it on the screen.

window.addEventListener('load', function(){
    RenderChat()
});

const chatObjectScriptsToUrlParams = (obj) =>{
    let params = "";
    for (var key in obj) {
        if (params != "") {
            params += "&";
        }
        params += key + "=" + encodeURIComponent(obj[key]);
    }
    return params;
}

const RenderChat = () => {

    let divChat = document.getElementById('dv-chat');

    let params = {
        action: 'DvChat',
        nounce: DvChat_js.nounce,
        url: DvChat_js.dv_chat_ajax,
    };

    params = chatObjectScriptsToUrlParams(params);

    fetch(DvChat_js.url + '?' + params)
        .then((response) => {
            return response.text();
        })
        .then((html) => {
            divChat.innerHTML = html;
            console.log('HTML => ', html);
        })
        .catch( () => {

        })
        .finally(() => {
            RenderChat();
        });
}

as I said, it's a very simple way to do it, I would really like your help to know if this is really the best way, or if there are adjustments, something I can improve on this idea.

I've seen people using setInterval(); but I chose to use a recursive function to reduce the number of requests.

It's the first time I'm developing a chat, and I don't know if it's right to make so many requests the way I did, I ended up having serious doubts about the performance related to the infrastructure

答案1

得分: 0

这段代码,我认为有两个问题。

  1. 它会过载您的服务器和网络。移动用户会讨厌您,或者更糟糕的是,停止使用您的东西。

    如果您将定期轮询服务器 - 每隔一段时间访问一次 - 您需要在访问之间设置一些时间延迟。每五秒钟访问服务器一次,而不是立即访问。

  2. 如其所写,您具有无限递归,并将导致堆栈溢出。在现代浏览器中,这需要一些时间,因为它们具有大量可用内存。

    如果这是我的项目,我会使用类似以下未经调试的方法来解决这两个问题,使用 setInterval()

    window.addEventListener('DOMContentLoaded', function() {
      setInterval(RenderChat, 5000)
    });   
    

    这会每隔五秒钟(5000毫秒)调用您的RenderChat函数,从网页加载时开始。为使其正常工作,您必须消除在finally{}子句中的尾递归调用。

    您也可以使用异步函数解决无限递归问题,但这是另一天的话题。

这里还有另一个问题:看起来聊天记录 - 每次访问时获取的记录 - 随着聊天的进展会变得越来越长。我曾经在Slack聊天中参与过几个月的聊天。因此,您的日志可能会变得太长。

英文:

This code, I believe, has two problems.

  1. It WILL overload your server and network. Mobile users will hate you, or worse, stop using your stuff.

    If you will poll your server -- hit it every so often -- you need to put some sort of time delay in between hits. Hit the server every five seconds or something, not immediately.

  2. As written you have unbounded recursion and will get a, well, stack overflow. It takes a while for this to happen in modern browsers, because they have lots of memory available.

    If this were my project I'd solve both these problems with something like this, not debugged, using setInterval().

    window.addEventListener('DOMContentLoaded', function() {
      setInterval(RenderChat, 5000)
    });   
    

    This calls your RenderChat function every five seconds (5000 milliseconds), starting when the web page is loaded. You have to get rid of the tail recursion call in your finally{} clause for this to work.

    You could also solve the unbounded recursion problem with async functions, but that's a topic for another day.

There's another problem here: it looks like the chat log -- the one you fetch on every hit -- gets longer and longer as the chat progresses. I've been on Slack chats that last for months and months. So your logs might get too long.

答案2

得分: 0

对于这种类型的应用程序,我建议使用WebSocket连接以实现实时用户体验。无需轮询。当客户端收到信息时,它会更新服务器,反之亦然。

不确定PHP是否是这种类型应用的最佳服务器端语言,但有一个库:Ratchet,它应该能够满足你的需求。

英文:

For this type of application, I would recommend utilizing a websocket connection for a real-time user experience. No polling necessary. When the client receives info, it updates the server and visa-versa.

Not sure PHP is the best server-side language for this kind of app, but there is a library: Ratchet that should do what you need it to do.

huangapple
  • 本文由 发表于 2023年6月12日 00:40:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定