|
What this is
Other links
The source code/* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software * License version 1.1, a copy of which has been included with this * distribution in the LICENSE.txt file. */ package org.apache.log4j.performance; /** This program compares the cost of creating a new StringBuffer and converting it to a String versus keeping the same StringBuffer, setting its size to zero and then converting it to String.
The tests copy a message to a destination string buffer and then copy a 256 character buffer to another buffer the number of times as specified by the secondary loop length. The This is due to a peculiarity in the The tests were performed on Linux using IBM's JDK 1.1.8. The test script is a crude model of what might happen in reality. If you remain unconvinced of its results, then please send your alternative measurement scenario. */ public class NewVsSetLen { static String s; static int BIGBUF_LEN = 1048576; static int SBUF_LEN = 256; static int RUN_LENGTH = BIGBUF_LEN/4; static char[] sbuf = new char[SBUF_LEN]; static char[] bigbuf = new char[BIGBUF_LEN]; { for(int i = 0; i < SBUF_LEN; i++) { sbuf[i] = (char) (i); } for(int i = 0; i < BIGBUF_LEN; i++) { bigbuf[i] = (char) (i); } } static public void main(String[] args) { int t; for(int len = SBUF_LEN; len <= BIGBUF_LEN; len*=4, RUN_LENGTH /= 4) { System.out.println(" | "+len+"\n"); for(int second = 0; second < 16;) { System.out.println("SECOND loop="+second +", RUN_LENGTH=" +RUN_LENGTH+", len="+len); t = (int)newBuffer(len, second); System.out.print(" | " + t); t = (int)setLen(len, second); System.out.println(" | " + t + " \n"); if(second == 0) { second = 1; } else { second *= 2; } } } } static double newBuffer(int size, int second) { long before = System.currentTimeMillis(); for(int i = 0; i < RUN_LENGTH; i++) { StringBuffer buf = new StringBuffer(SBUF_LEN); buf.append(sbuf, 0, sbuf.length); buf.append(bigbuf, 0, size); s = buf.toString(); } for(int x = 0; x < second; x++) { StringBuffer buf = new StringBuffer(SBUF_LEN); buf.append(sbuf, 0, SBUF_LEN); s = buf.toString(); } return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH; } static double setLen(int size, int second) { long before = System.currentTimeMillis(); StringBuffer buf = new StringBuffer(SBUF_LEN); for(int i = 0; i < RUN_LENGTH; i++) { buf.append(sbuf, 0, sbuf.length); buf.append(bigbuf, 0, size); s = buf.toString(); buf.setLength(0); } for(int x = 0; x < second; x++) { buf.append(sbuf, 0, SBUF_LEN); s = buf.toString(); buf.setLength(0); } return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH; } } |
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.