Skip to content

Performance degradation when initializing arrays in loops #26511

@kostya

Description

@kostya

Describe the bug

In this benchmark: https://kostya.github.io/LangArena/
The AStarPathfinder benchmark executes in ~60s on:

I found that changing the init_scores function to an unsafe version reduces time to 3.3s (20x faster).

Here are the slow and fast functions from the source: https://github.com/kostya/LangArena/blob/d2e12f2e643ca69e93e635c5e0a8d13fad3722d3/v/astar_pathfinder.v#L169

// Slow version (~60s)
fn (mut b AStarPathfinder) init_scores(size int) {
    for i in 0 .. size {
        b.g_scores[i] = inf
        b.came_from[i] = -1
    }
}

// Fast version (~3.3s) - 20x faster
// fn (mut b AStarPathfinder) init_scores(size int) {
//     unsafe {
//         // Fill g_scores with inf
//         mut g_ptr := &b.g_scores[0]
//         for i in 0 .. size {
//             g_ptr[i] = inf
//         }
//
//         // Fill came_from with -1
//         mut c_ptr := &b.came_from[0]
//         for i in 0 .. size {
//             c_ptr[i] = -1
//         }
//     }
// }

I'm pretty sure this is unexpected behavior - the safe version shouldn't be 20x slower than the unsafe one for simple array initialization.

Reproduction Steps

git clone https://github.com/kostya/LangArena.git
cd LangArena/v
v install
./run AStarPathfinder

Expected Behavior

Fast version (~3.3s)

Current Behavior

Slow execution (~60s)

Possible Solution

use unsafe initialization

Additional Information/Context

No response

V version

V 0.5.0 6be2fbb

Environment details (OS name and version, etc.)

  • MacOS
  • Apple clang version 15.0.0 (clang-1500.3.9.4)

Note

You can use the 👍 reaction to increase the issue's priority for developers.

Please note that only the 👍 reaction to the issue itself counts as a vote.
Other reactions and those to comments will not be taken into account.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugThis tag is applied to issues which reports bugs.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions