Benchmarking Fibonacci performance on Android through deep recursion

Currently, I am conducting a Fibonacci benchmark on my Android phone and the results are quite unusual. Interestingly, I am not concerned about whether the UI-thread is locked or not, so I have decided to run the following code within the UI-thread of my application (could this potentially impact performance?).

public void startBenchmark(View view) {
        results = "";

        results += String.format("Begin test");
        for (int i = 45; i < 46; i++) {
            startTime = System.currentTimeMillis();
            fib(i);
            results += String.format("%d\n", System.currentTimeMillis() - startTime);
        }
        results += String.format("End test");
        Log.d("Results", results);


    Log.d("Status", "Finished");
}

private static int fib(int n) {
    return n <= 1 ? n : fib(n - 1) + fib(n - 2);
}

In addition, I have also created a similar code in JavaScript;

function performBenchmark() {

    for (var i = 45; i < 46; i++) {
        benchmark(i)
    }

}

function benchmark(n){
    var start= Date.now();
    document.getElementById("disp").innerHTML += "fib(" + n + "): " + fib(n) + " <br />";
    document.getElementById("results").innerHTML += (Date.now() - start) + "<br />";

}

function fib(n) {
    return n <= 1 ? n : fib(n - 1) + fib(n - 2);
}

I am encountering an issue with fib(45) where the native Java platform is taking around 420 seconds while JavaScript in Chrome only takes 120 seconds when running on my Samsung Galaxy Nexus.

Could there be a glaring issue in my Java implementation for Android that is causing this slowdown in the benchmark?

Note: My main focus is not on transitioning to a quicker algorithm but rather understanding why JavaScript (and even an iOS implementation I worked on) outperform the Java implementation for Android significantly.

Interestingly, when running the tests on my laptop, Java performs much faster than JavaScript.

Answer №1

Comparing highly inefficient code doesn't provide meaningful insights. The optimizations specific to each language may not accurately represent the efficiency of different programs.


Your solution in Java and JavaScript suffers from slow performance. Certain languages, like functional ones, can rearrange your code for better efficiency, but Java and JavaScript lack this capability.

private static int fib(int n) {
    return n <= 1 ? n : fib(n - 1) + fib(n - 2);
}

Consider this: achieving a result of 1134903170 requires numerous calls to this method (to reach both 1 and all intermediary values).

Note: The time complexity exponentially increases with the input value.

I recommend using iteration for improved speed in Java and JavaScript.

private static long fib(int n) {
    long a = 1, b = 1;
    while (--n > 1) {
        long c = a + b;
        a = b;
        b = c;
    }
    return b;
}

Note: The runtime is directly proportional to the value of n, such as 45 in this case.

Note 2: This algorithm is so concise that it doesn't even require JIT compilation.

public static void main(String... ignore) {
    for (int j = 0; j < 5; j++) {
        long fib = 0, start = System.nanoTime();

        int repeats = 2000;
        for (int i = 0; i < repeats; i++)
            fib = fib(45);
        long avgTime = (System.nanoTime() - start) / repeats;

        System.out.println(fib + " took an average of " + avgTime + " nano-seconds");
    }
}

This code snippet will display:

1134903170 took an average of 2695 nano-seconds
1134903170 took an average of 995 nano-seconds
1134903170 took an average of 90 nano-seconds
1134903170 took an average of 89 nano-seconds
1134903170 took an average of 89 nano-seconds

Note 3: The drastic decrease in runtime from 2695 nanoseconds to 89 nanoseconds is extraordinary and cannot be solely attributed to faster hardware.

Answer №2

Java-Code runs a total of 5 times, while JavaScript only runs once.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for aligning the timer on a client's webpage with the server

What is the most effective method to synchronize the time displayed on a webpage with the server? My webpage requires that a countdown begins simultaneously for all users and ends at precisely the same time to avoid any user gaining a time advantage. Whi ...

Can you explain the concept of ".el" as it relates to JavaScript, HTML, and jQuery?

After conducting a search on Google, I didn't find much information. Perhaps I am using the wrong terms. I am trying to figure out what the "el" in "$.el" represents in the following code snippet: $.el.table( $.el.tr( $.el.th('first name ...

javascript implementing number formatting during keyup event

When I try to format a number in an input field on the keyup event, I receive a warning in my browser console that says "The specified value "5,545" cannot be parsed, or is out of range." The value in the input field also gets cleared. How can I solve this ...

Customize dynamically loaded data via AJAX

I have a webpage that is loading a table from another source. The CSS is working fine, but I am facing an issue editing the table using jQuery when it's loaded dynamically through a script. It seems like my changes are not getting applied because they ...

When invoked, a Javascript Object comes back empty

My code snippet: const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results const channelList = channels.each(function (page) { ...

Leveraging Jquery to retrieve multiple values for dynamic updating in HTML

As I ponder over this dilemma, a suitable title eludes me to encapsulate my query. Behold the code in question: $(document).ready(function() { setInterval(function(){ $.get('/battleship/update_game/{{info.gameid}}/{{user.username}}', ...

What is the best way to retrieve a response from a modal dialog using jQuery?

Is there a way to utilize an add-in such as simple-modal or the dialog add-in in the UI kit to achieve AJAX interaction with the server? I am looking for a solution that allows the modal to communicate with the server and return the result back to the ca ...

Avoid repeating the same options in a dropdown menu

Here is the HTML code I am working with: <div layout="row" layout-align="center center"> <md-select placeholder="Property type" ng-model="id" md-on-open="loadProperties()" style="min-width: 200px; padding: 20px;"> ...

React state will only return a single element

I've been working on updating the state and using the updated state for rendering. After I click and make modifications (such as adding {isClicked: true} to an array), the console.log(this.state.listOfQuotes) within the onClicked function displays t ...

How can I obtain the index of the selected class name?

Is there a way to retrieve the index of a classname assigned to multiple input fields and then log it using console.log()? I've written this code snippet: document.querySelectorAll('.class-name').forEach(item => { item.addEventListene ...

Using nested ng-repeat on a single element to implement filtering

I've created a page with tiles, each consisting of a thumbnail and a title. Each tile can have multiple tags associated with it. For example: Tile 1 has the tags: foo, bar, baz, quz Tile 2 has the tags: foo, bar, baz Tile 3 has the tags: bar, baz T ...

Using JavaScript to Retrieve Image Sources

function validate(form) { while ($('#img').attr('src')=="../static/img/placeholder.png") { return false; } return true; } ^I'm having trouble with this code. I want my form to prevent submission as long as ...

Arranging data in a table using PHP

After some thorough research, I am finally prepared to dive into the world of PHP. My project involves an HTML5 animation with table sorting functionalities - one button for sorting by date and another for sorting by title. Despite my efforts to find a cus ...

Encountered a 404 error while attempting to build and serve a Vue.js project using 'npm build' in Apache Tomcat

After setting up a Vue.js project, the configuration in the package.json file looks like this: "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

Issue with Mongoose's deep population feature not functioning as expected

I'm currently working on a web application that requires the use of mongoose-deep-populate. I've already installed it using npm, but unfortunately, I keep encountering the following error: Error: Plugin was not installed at Query.deepPopulate (/ ...

Troubleshooting a Recursive Menu Problem in Vue.js

I've been attempting to create a recursive menu in Vue.js, but I keep encountering an error and I'm struggling to identify the issue. Here is my current structure: MenuList.vue <template> <ul class="menu"> <MenuLink v ...

Guide to dynamically populating a select dropdown in a Django template with Javascript

Recently, I started learning Django and HTML, but JavaScript is still quite new to me. I'm working on creating a database display page with a filter menu on the side. Here is the code for this particular page: Model.py: class Part(models.Model): ...

preserving web session in WebDriver

Utilizing Junit 4 and Selenium webdriver in my automation process, I am faced with a situation where multiple test cases necessitate login functionality. The issue at hand is running all the test cases in the same browser window while maintaining the logi ...

Is there a way to retrieve the dates from last month using jQuery?

Currently, I am unable to select past dates with the provided code. How can I adjust it to allow for selecting dates from previous months? let firstDay = new Date(); $('#date_filter_startmonthly').datepicker({ startDate: firstDay, endDate: ...