在Java中实现固定大小的非阻塞队列最有效的方法是什么?
我试图找到(或编写)一个代表固定大小、非阻塞、自动丢弃 FIFO 队列的 Java 类。 (例如,如果队列的容量为 100,则放入项目 101 会删除项目 1,然后成功追加项目 101。)这个问题似乎很有帮助,但我有一个额外的限制 - 我需要它很快,容量约为 100-1000。
我的队列中的项目只是浮点数,因此使用链接问题中描述的 AutoDiscardingDequefloat[] 和一些
System.arraycopy()
操作来处理它?
或者,还有我没有想到的更好的解决方案吗?
I am trying to find (or write) a Java class that represents a fixed-size, non-blocking, auto-discarding FIFO queue. (e.g. if the queue has a capacity of 100, putting item 101 removes item 1 then successfully appends item 101.) The answer to this question seems helpful, but I have an extra constraint - I need it to be fast, for capacities of around 100-1000.
The items in my queue are only Floats, so is it generally more efficient to use something like the AutoDiscardingDeque<Float>
described in the linked question, or just to use a float[]
and some System.arraycopy()
manipulation to handle it?
Alternatively, is there an even better solution that I haven't thought of?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只需要使用浮点数,那么是的,
float[]
将是实现中的最佳选择。您根本不需要复制数组 - 只需维护“开始位置”和“结束位置”。您已经知道容量,因此您可以从创建阵列开始,并且永远不会改变它。请注意,我并不是建议您使用
float[]
代替此处的队列 - 只是您可以使用实现队列代码>浮动[]。当然,这意味着您无法轻松地使其实现您可能想要的Deque
而不会产生装箱/拆箱成本……但如果您愿意只使用在您的客户端代码中使用具体的类,您最终将节省效率。If you only ever need to use floats, then yes, a
float[]
will be optimal in the implementation. You shouldn't need to copy the array at all - just maintain a "start position" and an "end position". You already know the capacity, so you can create the array to start with and never budge from it.Note that I'm not suggesting you use a
float[]
instead of a queue here - just that you can implement the queue using afloat[]
. Of course, that means you can't easily make it implementDeque<Float>
which you may want it to, without incurring boxing/unboxing costs... but if you're happy only ever using the concrete class within your client code, you'll end up with efficiency savings.如果您认为要在结构上执行许多与数学相关的函数,特别是平均值、最大值、最小值等统计函数,那么您可以使用 Apache Commons Math (http://commons.apache) 中的 DescriptiveStatistics .org/math/userguide/stat.html#a1.2_Descriptive_statistics)。您可以设置窗口大小,它会自动维护您的元素。然而,它需要双精度,而不是浮点数,所以它可能不是您的完美解决方案。
If you think you are going to want to perform a number of math related functions on your structure, specifically statistics functions like mean, max, min, ect., then you could use DescriptiveStatistics from Apache Commons Math (http://commons.apache.org/math/userguide/stat.html#a1.2_Descriptive_statistics). You can set your window size and it will automatically maintain your elements. However it takes doubles, not floats, so it might not be the perfect solution for you.
请具体说明您需要快速执行哪些操作?实施对于您将如何使用它非常敏感。
如果您需要经常通过索引访问它,那么上面的解决方案似乎足够好了
Please, specify, which operations you need to be fast? Implementation is very sensible to how you are going to use it.
If you need accessing it by index very often, than the solution above seems good enough