Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit e0961b7

Browse filesBrowse files
Merge pull request giantray#1 from zhongjianluxian/why-is-printing-b-dramatically-slower-than-printing
Create why-is-printing-b-dramatically-slower-than-printing.md
2 parents 7856e30 + 342ea67 commit e0961b7
Copy full SHA for e0961b7

File tree

Expand file treeCollapse file tree

1 file changed

+64
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+64
-0
lines changed
+64Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# 为什么打印“B”会明显的比打印“#”慢
2+
3+
## 问题
4+
5+
我生成了两个`1000`x`1000`的矩阵:
6+
7+
第一个矩阵:`O``#`
8+
第二个矩阵:`O``B`
9+
10+
使用如下的代码,生成第一个矩阵需要8.52秒:
11+
12+
Random r = new Random();
13+
for (int i = 0; i < 1000; i++) {
14+
for (int j = 0; j < 1000; j++) {
15+
if(r.nextInt(4) == 0) {
16+
System.out.print("O");
17+
} else {
18+
System.out.print("#");
19+
}
20+
}
21+
22+
System.out.println("");
23+
}
24+
25+
26+
而使用这段代码,生成第二个矩阵花费了259.152秒:
27+
28+
Random r = new Random();
29+
for (int i = 0; i < 1000; i++) {
30+
for (int j = 0; j < 1000; j++) {
31+
if(r.nextInt(4) == 0) {
32+
System.out.print("O");
33+
} else {
34+
System.out.print("B"); //only line changed
35+
}
36+
}
37+
38+
System.out.println("");
39+
}
40+
41+
如此大的运行时间差异的背后究竟是什么原因呢?
42+
43+
---
44+
45+
正如评论中所建议的,只打印`System.out.print("#");`用时7.8871秒,而`System.out.print("B");`则给出`still printing...`
46+
47+
另外有人指出这段代码对他们来说是正常的, 我使用了[Ideone.com](http://ideone.com),这两段代码的执行速度是相同的。
48+
49+
测试条件:
50+
51+
- 我在Netbeans 7.2中运行测试,由控制台显示输出
52+
- 我使用了`System.nanoTime()`来计算时间
53+
54+
## 解答
55+
56+
*纯粹的推测*是因为你使用的终端尝试使用[单词换行][1]而不是字符换行,并且它认为`B`是一个单词而`#`却不是。所以当它到达行尾并且寻找一个换行的地方的时候,如果是`#`就可以马上换行;而如果是`B`,它则需要花更长时间搜索,因为可能会有更多的内容才能换行(在某些终端会非常费时,比如说它会先输出退格再输出空格去覆盖被换行的那部分字符)。
57+
58+
但这都只是纯粹的推测。
59+
60+
61+
[1]: http://en.wikipedia.org/wiki/Word_wrap
62+
63+
64+
stackoverflow原址:http://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.