Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

javascript - Best way to add an event listener on socket.io to save resources

So i'm trying to know how javascript handles function.

if i have a code like this:

io.on("connection", function(socket) {
  socket.on("hi", function(data) {
    socket.emit("emit", "hey")
  })
})

What's in my mind is that each new connection, javascript will create another function for the "hi" event. So what I'm currently doing in my app is like this:

function hi(data) {
    this.emit("emit", "hey")
}

io.on("connection", function(socket) {
  socket.on("hi", hi)
})

This way javascript will just reuse the function hi instead of instancing a new one?? I'm not sure if this is necessary but I want to consume less resources as much as possible because I'm thinking about what will happen when the server have thousand of connections.

question from:https://stackoverflow.com/questions/65833857/best-way-to-add-an-event-listener-on-socket-io-to-save-resources

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Functions in JavaScript are considered as objects, and as such, they are of reference type. We can tell by doing a simple test like this:

const a = () => {};
const b = () => {};
const c = a;

console.log(a === b); // false
console.log(a === c); // true

Whenever a new connection is created in your case, a reference of the function is passed as the callback, which means that every connection would be calling the same memory address where the function was initially stored. So your implementation is correct, you don't have to worry about the possibility of using huge amounts of memory in this case :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...