Skip to content

fancynpcs: Optimize NPC lookup by id - #303

Open
JuliGame wants to merge 1 commit into
FancyInnovations:mainfrom
JuliGame:fix/fancynpcs-v2-get-npc-by-id
Open

fancynpcs: Optimize NPC lookup by id#303
JuliGame wants to merge 1 commit into
FancyInnovations:mainfrom
JuliGame:fix/fancynpcs-v2-get-npc-by-id

Conversation

@JuliGame

Copy link
Copy Markdown

📋 Description

Optimized getNpcById from O(N) to O(1).

✅ Checklist

  • My code follows the project's coding style and guidelines
  • I have tested my changes locally and they work as expected
  • I have added necessary documentation (if applicable)
  • I have linked related issues using Fixes #issue_number or Closes #issue_number
  • I have rebased/merged with the latest main branch

🔍 Changes

Changed fancynpcs-v2\src\main\java\de\oliver\fancynpcs\NpcManagerImpl.java from

    @Override
    public Npc getNpcById(String id) {
        for (Npc npc : getAllNpcs()) {
            if (npc.getData().getId().equals(id)) {
                return npc;
            }
        }

        return null;
    }

to

    @Override
    public Npc getNpcById(String id) {
        return npcs.get(id);
    }

This is free as Map<String, Npc> npcs is already a map with the ID as key, this preserves the existing behavior avoiding the linear scan.

Performance before the change:
image


🧪 How to Test

  1. use getNpcById
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant