Java 中读取/解析控制台输入、Scanner 或 BufferedReader 哪个更快?

发布于 2024-12-06 02:06:31 字数 200 浏览 0 评论 0原文

我必须设计一个数据处理器,能够处理来自 STDIN 的超过 2.5MB/s 的输入,并向 STDOUT 输出一个数字。使用 BufferedReader 然后转换为数据类型或 Scanner 以及 nextInt() 或 nextFloat() 哪个更快?

实证测试结果:BufferedReader 和转换速度稍快一些,但没有什么太大的意义。

谢谢你!

I have to craft a data processor able to process more than 2.5MB/s of input from STDIN, and output a number to STDOUT. What is faster, to use a BufferedReader and then conversions to data types or a Scanner and nextInt() or nextFloat()?

EMPIRICAL TEST RESULTS: BufferedReader and conversion is a little bit faster, but nothing too significant.

Thankyou!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陪我终i 2024-12-13 02:06:31

答案很可能是,从性能角度来看,采用哪种方式并不重要。 (而且某人不可能在控制台上以每秒 2.5Mb 的速度打字!)

如果您将操作系统级别和其他地方在从控制台读取数据时发生的所有事情都包括在内,则 CPU 数量级会增加从用户在控制台输入的字节中获取字节所花费的周期将多于解析字符所花费的周期。如果您正在从文件中读取(通过标准输入),我们不再谈论数量级差异,但如果这两种方法总体上有显着不同,我仍然会感到惊讶。

但你能做的最好的事情就是尝试一下。编写一个大致接近您正在做的事情的基准测试应该不会超过几分钟,然后看看哪种替代方案更快……以及快了多少。 (确保您测量的是总运行时间,而不仅仅是 Java 应用程序的用户空间 CPU 时间。)

The answer is most likely that it doesn't matter which way you do it from a performance perspective. (And there's no way that someone can type at 2.5Mb per second at the console!)

If you include everything that goes on at the OS level and elsewhere when reading from the console, orders of magnitude more CPU cycles will be expended in getting the bytes from the user typing at the console than are spent parsing the characters. If you are reading from a file (via stdin), we are no longer talking orders of magnitude difference, but I'd still be surprised if the two approaches were significantly different ... overall.

But the best thing you can do is try it out. It shouldn't take more than a few minutes to write a benchmark that roughly approximates to what you are doing, and see which alternative is faster ... and by how much. (Make sure that you measure total elapsed time, not just user-space CPU time for the Java application.)

二手情话 2024-12-13 02:06:31

BufferedReader 读取流。而扫描器将其输入分解为令牌。

2.5MB/s 更适合 BufferedReader。它具有比扫描仪更大的缓冲区。 8 比 1

BufferedReader >>>>>

BufferedReader reads the stream. While a Scanner breaks its input into tokens.

2.5MB/s is more suitable for the BufferedReader. It has a larger buffer than Scanner. 8 to 1

BufferedReader >>>>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文