【发布时间】:2013-11-21 11:18:34
【问题描述】:
对!这是我对循环缓冲区的尝试(用于图形程序,使用 canvas 元素)。还没有开始测试它。
问题是 - 谁能看出我的逻辑有任何缺陷?还是瓶颈?
/**
* A circular buffer class.
* @To add value -> bufferObject.addValue(xValue, yValue);
* @To get the First-in value use -> bufferObject.getValue(0);
* @To get the Last-in value use -> bufferObject.getValue(bufferObject.length);
**/
var circularBuffer = function (bufferSize) {
this.bufferSize = bufferSize;
this.buffer = new Array(this.bufferSize); // After testing on jPerf -> 2 x 1D array seems fastest solution.
this.end = 0;
this.start = 0;
// Adds values to array in circular.
this.addValue = function(xValue, yValue) {
this.buffer[this.end] = {x : xValue, y: yValue};
if (this.end != this.bufferSize) this.end++;
else this.end = 0;
if(this.end == this.start) this.start ++;
};
// Returns a value from the buffer
this.getValue = function(index) {
var i = index+this.start;
if(i >= this.bufferSize) i -= this.bufferSize; //Check here.
return this.buffer[i]
};
// Returns the length of the buffer
this.getLength = function() {
if(this.start > this.end || this.start == this.bufferSize) {
return this.xBuffer.length;
} else {
return this.end - this.start;
}
};
// Returns true if the buffer has been initialized.
this.isInitialized = function() {
if(this.end != this.start) return true;
else return false;
};
}
请随意重用此代码。
更新了两次(并经过测试!)。
【问题讨论】:
-
是的,在 this.getValue 中计算缓冲区的索引过于频繁。 x 和 y 对一起运行,所以你应该能够得到 point = this.buffer[index]; y = point.y x=point.x 或类似的。
-
感谢您的快速回复!不确定我是否完全理解它。喝完这杯咖啡可能对我更有意义。
-
知道了。你的意思是添加一个变量... [convertIndex = index+this.start;] 然后重用它。如果是这样,完成。谢谢!
-
我的性感重写 -> [ this.getValue = function(index) { var i = index+this.start; if(i >= this.bufferSize) i -= this.bufferSize;返回 { x : this.xBuffer[i], y : this.yBuffer[i], }; };]
-
这是一个开始:-),但我认为您也可以将 xBuffer 和 yBuffer 合并到简单的缓冲区中。最好在进行更改时编辑您的原始问题,并简单地记下您已对其进行了更新
标签: circular-buffer