java读取输入
我有两种类型的输入数据
a b c d e...
,这里 a、b 等是要读取的值。所有数据类型都相同,可以是短整型、整型、长整型、双精度型。所有值均由一个或多个空格分隔。我们在一行中给出了这些,但我们不知道有多少。输入以换行符结束。在第二种情况下,我们将 count 作为第一个变量“n”,然后是 n 个变量。例如,对于 n=5,它看起来像这样。
n a b c d e
这可以使用 Scanner 来完成,但我听说用 Scanner 读取输入比 bufferedReader 方法慢。除了使用 Scanner 类之外,我正在寻找任何可能的方法来执行此操作。我是 Java 新手。请帮忙。
I've two types of input data
a b c d e...
Here a, b, and so on are values to be read. All are of same data types which may be short, int, long, double. All values are separated by one or more spaces. We've given these on a single line and we don't know how many are there. Input ends with newline. In second case we're given count as a first variable "n" and then n variables follow. e.g. for n=5, it looks like this.
n a b c d e
This could be done with Scanner but I've heard reading input with scanner is slower than bufferedReader method. I'm looking for any possible way for doing this other than using Scanner class. I'm new to Java. Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会先得到一些有效的东西。一旦了解了瓶颈,才值得尝试优化它。
为了回答你的问题,恕我直言,读取数据的最快方法是使用内存映射文件并解析 ByteBuffer,假设你有 ASCII 8 位字节数据(对数字的合理假设),避免完全使用内置解析器。这会快得多,但对于更复杂和彻底的杀伤力来说也很多。 ;)
如果您想要如何直接从 ByteBuffer 解析数字的示例 Java 低级:整数和文本之间的转换(第 1 部分) 为了更快,您可以使用 Unsafe 类,但这不是标准的 Java。
I would get something which works first. Once you have an understanding of the bottleneck, only then is it worth trying to optimise it.
To answer your question, IMHO, the fastest way to read the data is to use a memory mapped file and parse the ByteBuffer assuming you have ASCII 8-bit byte data (a reasonable assumption for numbers) avoiding using the built in parsers altogether. This will be much faster but also a lot for more complicated and complete overkill. ;)
If you want examples of how to parse numbers straight from a ByteBuffer Java low level: Converting between integers and text (part 1) To go faster you can use the Unsafe class, but that is not standard Java.
特别是当您刚接触一种语言或环境时,我建议您从一些易于理解但功能强大的东西开始,例如
当然要通过一定量的错误检查来完成!
之后,如果您确定(通过证据,例如应用程序分析的输出)该部分代码实际上导致了不合理的 CPU 消耗,您可以开始考虑更快、更自定义的读取数据的方法。反之则不然。
Especially when you're new to a language or environment I would suggest to start out with something easily understood yet functional like
Of course to be completed with a healthy dose of error checking!
Afterwards, if you determine (with proof, eg the output of the profiling of your app) that that part of the code is in fact responsible for an unreasonable amount of CPU consumption you can start thinking about faster, more custom ways of reading the data. Not the other way around.