Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8474779
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T17:42:58+00:00 2026-06-10T17:42:58+00:00

Can anyone explain why the following recursive method is faster than the iterative one

  • 0

Can anyone explain why the following recursive method is faster than the iterative one (Both are doing it string concatenation) ? Isn’t the iterative approach suppose to beat up the recursive one ? plus each recursive call adds a new layer on top of the stack which can be very space inefficient.

    private static void string_concat(StringBuilder sb, int count){
        if(count >= 9999) return;
        string_concat(sb.append(count), count+1);
    }
    public static void main(String [] arg){

        long s = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 9999; i++){
            sb.append(i);
        }
        System.out.println(System.currentTimeMillis()-s);
        s = System.currentTimeMillis();
        string_concat(new StringBuilder(),0);
        System.out.println(System.currentTimeMillis()-s);

    }

I ran the program multiple time, and the recursive one always ends up 3-4 times faster than the iterative one. What could be the main reason there that is causing the iterative one slower ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T17:43:00+00:00Added an answer on June 10, 2026 at 5:43 pm

    See my comments.

    Make sure you learn how to properly microbenchmark. You should be timing many iterations of both and averaging these for your times. Aside from that, you should make sure the VM isn’t giving the second an unfair advantage by not compiling the first.

    In fact, the default HotSpot compilation threshold (configurable via -XX:CompileThreshold) is 10,000 invokes, which might explain the results you see here. HotSpot doesn’t really do any tail optimizations so it’s quite strange that the recursive solution is faster. It’s quite plausible that StringBuilder.append is compiled to native code primarily for the recursive solution.

    I decided to rewrite the benchmark and see the results for myself.

    public final class AppendMicrobenchmark {
    
      static void recursive(final StringBuilder builder, final int n) {
        if (n > 0) {
          recursive(builder.append(n), n - 1);
        }
      }
    
      static void iterative(final StringBuilder builder) {
        for (int i = 10000; i >= 0; --i) {
          builder.append(i);
        }
      }
    
      public static void main(final String[] argv) {
        /* warm-up */
        for (int i = 200000; i >= 0; --i) {
          new StringBuilder().append(i);
        }
    
        /* recursive benchmark */
        long start = System.nanoTime();
        for (int i = 1000; i >= 0; --i) {
          recursive(new StringBuilder(), 10000);
        }
        System.out.printf("recursive: %.2fus\n", (System.nanoTime() - start) / 1000000D);
    
        /* iterative benchmark */
        start = System.nanoTime();
        for (int i = 1000; i >= 0; --i) {
          iterative(new StringBuilder());
        }
        System.out.printf("iterative: %.2fus\n", (System.nanoTime() - start) / 1000000D);
      }
    }
    

    Here are my results…

    C:\dev\scrap>java AppendMicrobenchmark
    recursive: 405.41us
    iterative: 313.20us
    
    C:\dev\scrap>java -server AppendMicrobenchmark
    recursive: 397.43us
    iterative: 312.14us
    

    These are times for each approach averaged over 1000 trials.

    Essentially, the problems with your benchmark are that it doesn’t average over many trials (law of large numbers), and that it is highly dependent on the ordering of the individual benchmarks. The original result I was given for yours:

    C:\dev\scrap>java StringBuilderBenchmark
    80
    41
    

    This made very little sense to me. Recursion on the HotSpot VM is more than likely not going to be as fast as iteration because as of yet it does not implement any sort of tail optimization that you might find used for functional languages.

    Now, the funny thing that happens here is that the default HotSpot JIT compilation threshold is 10,000 invokes. Your iterative benchmark will more than likely be executing for the most part before append is compiled. On the other hand, your recursive approach should be comparatively fast since it will more than likely enjoy append after it is compiled. To eliminate this from influencing the results, I passed -XX:CompileThreshold=0 and found…

    C:\dev\scrap>java -XX:CompileThreshold=0 StringBuilderBenchmark
    8
    8
    

    So, when it comes down to it, they’re both roughly equal in speed. Note however that the iterative appears to be a bit faster if you average with higher precision. Order might still make a difference in my benchmark, too, as the latter benchmark will have the advantage of the VM having collected more statistics for its dynamic optimizations.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can anyone explain the following immediate window behavior: Debug.Print mDb.DatabaseOptions Method arguments must be
Can anyone explain if there is any benefit in either one of the following
Can anyone explain why the following two statements both evaluate as true ? []
Can anyone explain exactly why Method 1 in the following code does not alter
Can anyone explain why the following occurs: String.Format(null, foo) // Returns foo String.Format((string)null, foo)
Can anyone explain the following PHP Code ? function get_param($param_name, $param_type = 0) {
Can anyone explain the following behaviour to a relative newbie... const char cInputFilenameAndPath[] =
I am new to Perl, can anyone explain the following scripts for me please:
Can anyone explain what the following PHP Code does function query($query_string) { if ($query_string
Can anyone explain why the following jquery only fires the 2nd toggle event and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.