001package algs14;
002import stdlib.*;
003public class XPerformanceOfStrings {
004        /** create a string consisting of N asterisks */
005        public static String makeStringUsingConcat (int N) {
006                String result = "";
007                for (int i=0; i<N; i+=1) {
008                        result = result + "*";
009                        ops += result.length();
010                }
011                return result;
012        }
013        /** create a string consisting of N asterisks */
014        public static String makeStringUsingBuffer (int N) {
015                StringBuffer result = new StringBuffer ();
016                for (int i=0; i<N; i+=1) { 
017                        result.append ("*");
018                        ops += 1;
019                }
020                return result.toString ();
021        }
022        private static long ops;
023        private static String result;
024        public static void main(String[] args) {
025                timeTrial(32);
026                StdOut.println(result);
027                
028                int MIN = 256; 
029                int MAX = 1_000_000_000;
030                double prevTime = timeTrial(MIN);
031                double prevOps = ops;
032                for (int N = MIN*2; N<=MAX; N += N) {
033                        double time = timeTrial(N);
034                        StdOut.format ("Elapsed count f(%,13d): %,17d: %10.3f [%10.3f : %10.3f]\n", N, ops, ops / prevOps, time, time/prevTime);
035                        prevTime = time;
036                        prevOps = ops;
037                }
038        }
039        public static double timeTrial(int N) {
040                ops = 0;
041                Stopwatch sw = new Stopwatch();
042                result = makeStringUsingConcat(N);
043                //result = makeStringUsingBuffer(N);            
044                return sw.elapsedTime();
045        }
046}