1

Can anyone help to reduce time to run this code?

It's not an actual code, it's just a part of one of my project:

import java.util.*;

class testing{
    public static void main(String[] args) {
        String s="";

        for(long i=0L;i<10000000000L;i++)
            s+=String.valueOf(Character.toChars((int)(Math.random()*26+97)));

        System.out.println(s.length()+"\n"+s);
    }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140

4 Answers4

4

1) Instantiate StringBuilder by setting the wished capacity :

 new StringBuilder(wishedSize)

2) You create a random double but you cast it to int :

(int)(Math.random()*26+97)

So you can use instead your own Random object before the loop and invoke nextInt().

3) As Andy underlines (I didn't notice it) you get at the end a series of lower case letters.
You could use a Random.nextInt(int) to get a number between 97 and 122 (unicode range for small letters) such as :

final int maxRange = 122 - 97;
Random random = new Random();
for (long i = 0L; i < 100L; i++) {
    int codePoint = random.nextInt(maxRange) + 97;
    // ...
}

Besides, in this way you perform only 1 arithmetic computation on the returned random value instead of 2 of them previously.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
1

You create a lot of Strings and concatenate them, which is quite slow.

Using a StringBuilder can be faster, if the expected size is known prior to generating the string:

StringBuilder sb = new StringBuilder(expectedStringLength);

for (int i = 0; i < expectedStringLength; i++)
    sb.append(Math.random() * 26 + 97);

System.out.println(sb.length() + "\n" + sb.toString());

Note however, that the length of the string cannot be bigger than Interger.MAX_VALUE, since it is backed by an array and java only supports int indices. Then again having such a big string will use a lot of memmory, so you might need to change your concept.

Pinkie Swirl
  • 2,375
  • 1
  • 20
  • 25
1

To prevent the crash, bypass the string entirely and dump it directly to filesystem.

try (OutputStream out = new OutputStreamWriter(new FileOutputStream(file)), "utf-8") {
    for (int i = 0; i < 100000000L; i++) {
        out.write(Character.toChars((int)(Math.random()*26+97)));
    }
    out.flush();
}
killjoy
  • 3,665
  • 1
  • 19
  • 16
0

Every string you make is immutable, so adding on to strings causes a lot of churn. Use a buffer, like this

class testing{
public static void main(String[] args) {
    StringBuffer sb = new StringBuffer(EST_SIZE);

    for(long i=0L;i<COUNT;i++)
        sb.append( Integer.toString(Math.random()*26+97 ) );

System.out.println(sb.length()+"\n"+sb.toString());
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Micromuncher
  • 903
  • 7
  • 19