Question about tuning Java IO performance

I am trying to optimize a web application that writes a lot to a stream. The code looks something like this:

 StringWriter stringWriter = new StringWriter(1024);
 PrintWriter printWriter = new PrintWriter(stringWriter);

This scriptwriter is then used to perform many write operations in several places, for example -

 printWriter.write("set interface ethernet0 zone Trust");

I want to optimize several write operations by wrapping a seal around the buffer. Therefore, I plan to change line1 and line2 as shown below. Please let me know if the approach below is correct -

StringWriter stringWriter = new StringWriter(1024);
// go for bufferedwriter instead of printwriter.
BufferedWriter bufWriter = new BufferedWriter(stringWriter, 8*1024); 

Also, I think that now I can replace the write method directly, as in -

printWriter.write("set interface ethernet0 zone Trust");

replaced as

bufWriter.write("set interface ethernet0 zone Trust");

Please let me know if this is correct or I need to use any of the overloaded BufferedWriter methods to make full use of BufferedWriter.

Thanks Dev

+3
source share
4

BufferedWriter char. StringWriter, , .

StringWriter Buffer , BufferedWriter . StringWriter.

+3

StringWriter ( ) , BufferedWriter . (- - JIT.)

-, , .

, -, ? ,

  • ( , ? ).
  • ( : " - " ).
  • , , , , , .
  • , , ( : "" , ).
+10

StringWriter? StringWriter - - StringBuffer, append.

StringBuilder. (, , ), - .

edit: , PrintWriter. , print/write, . , , .

: PrintWriter, : , PrintWriter - . , SAME , - , .

    ByteArrayOutputStream out = new ByteArrayOutputStream(bufSize);

    PrintWriter writer = new PrintWriter(out);

    synchronized (writer) {
        // do writes
    }

    writer.flush(); // very important or you may not see any output in 'out'
    writer.close();

    String output = out.toString();

PrintWriter, StringWriter.

    StringWriter writer = new StringWriter(bufSize);

    synchronized(writer.getBuffer()) {
        // do writes
    }

    writer.flush();
    writer.close();

    String output = writer.toString();

:

    StringBuilder builder = new StringBuilder();

    // do APPENDS (instead of writes)

    String output = builder.toString();

append , .

+3

I really doubt that it BufferedWriterwill give some kind of performance improvement here - and he, and StringWriterwrite directly to the memory. If something does, it will slow things down (fractionally) by adding a layer of indirection. Of course, if you find it differently, please correct me. What makes you think this is a bottleneck?

0
source

Source: https://habr.com/ru/post/1785902/


All Articles