全局范围或重复函数中的常数变量
我正在使用三分js建造一个虚拟空间,集成了3D资产和空间声音,因此它可能会受到挑战。我有一个在每个帧(每1/60秒)处调用的函数,我想知道将恒定变量放在哪里,以便它花费尽可能少的资源。
我认为我应该更好地将其放在全球范围中,因此不会在每个帧中再次分配它。但是我了解到,我应该尽可能避免“污染”全局范围,并且仅在给定功能中需要此变量。
那么,我应该把它放在全球范围内,因此污染了一点?是否每次重新分配它并从全球范围中读取相同的性能?
这是提供一些见解的功能,常数变量为easing_factor
:
function easeTransition(current, old) {
const EASING_FACTOR = 100;
let result = {};
for (const arg in current) {
const diff = current[arg] - old[arg];
result[arg] = old[arg] + diff / EASING_FACTOR;
}
return result;
}
谢谢!
I'm building a virtual space with Three.js, integrating 3D assets and spatial sound, so it can be quite performance-challenging. I have a function that is called at each frame (each 1/60 second), and I was wondering where to put the constant variables, for it to spend as little resources as it could.
I'm thinking I should better put it in the global scope, so it won't be assigned again at each frame. But I've learned I should avoid "polluting" the global scope as much as I can, and this variable is required only in that given function.
So, should I put it in the global scope, therefore polluting it a little ? Are re-assigning it each time and reading it from the global scope the same, performance-wise ?
Here is the function to provide some insight, the constant variable is EASING_FACTOR
:
function easeTransition(current, old) {
const EASING_FACTOR = 100;
let result = {};
for (const arg in current) {
const diff = current[arg] - old[arg];
result[arg] = old[arg] + diff / EASING_FACTOR;
}
return result;
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
划分比乘法慢,因此计算一次逆,然后进行数千个乘法而不是分隔是很有意义的。
其他模式应帮助您避免污染全球范围。实际上,我不确定这里的术语(哪种模块等),但是如果此代码在一个文件中,您只会导出
peretransition
函数,因此您的常数实际上不会是全局。如果要尝试“手动”此操作,则会使用IIFE:
consting_factor
现在在“闭合”中,而您唯一暴露的就是内部功能。Divisions are slower than multiplications, so it would make sense to compute the inverse once and then do thousands of multiplications instead of divisions.
Other patterns should help you avoid polluting the global scope. I'm actually not sure about the terminology here (what kind of modules etc) but if this code is in one file, you would only export the
easeTransition
function, thus your constants wouldn't actually be global.If you want to try this "manually" you would use an IIFE:
const EASING_FACTOR
is now in a "closure" and the only thing you expose is the inner function.