CSC300: PerformanceOfStrings [11/13] Previous pageContentsNext page

Strings are typically implemented as arrays of characters.

file:PerformanceOfStrings.java [source]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package ds1.student.orderofgrowth;

import stdlib.StdOut;
import stdlib.Stopwatch;

public class PerformanceOfStrings {
    /** create a string consisting of N asterisks */
    public static String makeStringUsingConcat (int N) {
        String result = "";
        for (int i=0; i<N; i+=1) {
            result = result + "*";
            ops += result.length();
        }
        return result;
    }
    /** create a string consisting of N asterisks */
    public static String makeStringUsingBuilder (int N) {
        StringBuilder result = new StringBuilder ();
        for (int i=0; i<N; i+=1) { 
            result.append ("*");
            ops += 1;
        }
        return result.toString ();
    }
    private static long ops;
    private static String result;
    public static void main(String[] args) {
        timeTrial(32);
        StdOut.println(result);
        
        int MIN = 256; 
        int MAX = 1_000_000_000;
        double prevTime = timeTrial(MIN);
        double prevOps = ops;
        for (int N = MIN*2; N<=MAX; N += N) {
            double time = timeTrial(N);
            StdOut.format ("Elapsed count f(%,13d): %,17d: %10.3f [%10.3f : %10.3f]\n", N, ops, ops / prevOps, time, time/prevTime);
            prevTime = time;
            prevOps = ops;
        }
    }
    public static double timeTrial(int N) {
        ops = 0;
        Stopwatch sw = new Stopwatch();
        result = makeStringUsingConcat(N);
        //result = makeStringUsingBuilder(N);
        return sw.elapsedTime();
    }
}

Previous pageContentsNext page