1

I have this program:

public class Duplicates {
    public static void main(String[] args) {
        byte[] bytes = "hz".getBytes();
        for (int i = 0; i < 10_000_000; i++) {
            System.out.write(bytes, 0, bytes.length);
        }
    }
}

After start I have output:

hzhzhzhzhzhzhzhz.....hz

But if I try convert int to byte array and print:

public class Duplicates {
    public static void main(String[] args) {
        byte[] bytes = ByteBuffer.allocate(4).putInt(666).array();
        for (int i = 0; i < 10_000_000; i++) {
            System.out.write(bytes, 0, bytes.length);
        }
    }
}

After start I have output:

� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

I want to print 666 10,000,000 times on each line of console and not use more than 20MB memory or 1 second.

What am I doing wrong?

EDIT If I will use example @Justin - Integer.toString(i).getBytes() I have this:

enter image description here

ip696
  • 6,574
  • 12
  • 65
  • 128

2 Answers2

1

The problem you are facing is not the call to Integer.valueOf(666).toString() since it is executed only once. The actual problem is, that the call to System.out.write() has some overhead. This can be avoided by using a larger buffer which is filled with some repetitions of the input value.

Here is what I came up with:

long start = System.currentTimeMillis();
byte[] bytes = String.valueOf(666).getBytes();

// use 20 mb of memory for the output buffer
int size = 20 * 1000 * 1000  / bytes.length;


byte[] outBuffer = new byte[size * bytes.length];
// fill the buffer which is used for System.out.write()
for (int i = 0; i < size; i++) {
    System.arraycopy(bytes, 0, outBuffer, i * bytes.length, bytes.length);
}

// perform the actual writing with the larger buffer
int times = 10_000_000 / size;
for (int i = 0; i < times; i++) {
    System.out.write(outBuffer, 0, outBuffer.length);
}
long end = System.currentTimeMillis();
System.out.println();
System.out.println("Took " + (end - start) + "Millis");

Which takes about 600ms to output 666 ten million times.

Jannik
  • 1,583
  • 1
  • 14
  • 22
0

That looks correct. If you cast int 666 to a char, that's what would be displayed. If you want to literally print out 666, you would need to convert the int to a String first:

byte[] bytes = Integer.toString(input).getBytes();
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Justin
  • 1,356
  • 2
  • 9
  • 16