Why is printing “B” dramatically slower than printing “#”?


SUBMITTED BY: menamagice

DATE: Aug. 9, 2017, 2:13 a.m.

FORMAT: Text only

SIZE: 1.3 kB

HITS: 303

  1. I generated two matrices of 1000 x 1000:
  2. First Matrix: O and #.
  3. Second Matrix: O and B.
  4. Using the following code, the first matrix took 8.52 seconds to complete:
  5. Random r = new Random();
  6. for (int i = 0; i < 1000; i++) {
  7. for (int j = 0; j < 1000; j++) {
  8. if(r.nextInt(4) == 0) {
  9. System.out.print("O");
  10. } else {
  11. System.out.print("#");
  12. }
  13. }
  14. System.out.println("");
  15. }
  16. With this code, the second matrix took 259.152 seconds to complete:
  17. Random r = new Random();
  18. for (int i = 0; i < 1000; i++) {
  19. for (int j = 0; j < 1000; j++) {
  20. if(r.nextInt(4) == 0) {
  21. System.out.print("O");
  22. } else {
  23. System.out.print("B"); //only line changed
  24. }
  25. }
  26. System.out.println("");
  27. }
  28. What is the reason behind the dramatically different run times?
  29. As suggested in the comments, printing only System.out.print("#"); takes 7.8871 seconds, whereas System.out.print("B"); gives still printing....
  30. As others who pointed out that it works for them normally, I tried Ideone.com for instance, and both pieces of code execute at the same speed.
  31. Test Conditions:
  32. I ran this test from Netbeans 7.2, with the output into its console
  33. I used System.nanoTime() for measurements

comments powered by Disqus