-2

I will be receiving strings one by one from a framework, I need to hold them in some container and delete some of them later. Now I have 2 options :-

  1. Create a slice of strings and then delete some items by look up
  2. Create a map of string with key=string and data=dummy data so that deletion is easy

So personally I would prefer second option. Is that correct choice? Do we have any better way?

3
  • Use map[string]bool for optimal clearness and speed. Commented May 10, 2021 at 4:58
  • map[string]struct{} is often preferred over map[string]bool because it is more semantically correct. Nobody reading your code will ever be left wondering "what does true/false mean?" Although some people prefer bool even so, because it's easier to type. Either works fine. struct{} is also slightly more memory-efficient. Commented May 10, 2021 at 9:04
  • How many strings are you dealing with? If it's less than 10 or so, a slice may be just fine. Or even if it's up to a few hundred, a slice may be okay if the number of deletions is low, especially if you have to convert from a map back to a slice for some reason. Commented May 10, 2021 at 9:05

1 Answer 1

2

If you need to access and delete strings by value, then a map[string]struct{} would give you better performance provided the number of strings is large enough and there are no duplicates. If there are duplicates and when you delete you have to delete only one, then a map[string]int would work, with the value being the number of times the string appears. If the number of strings are not large, then a container/list might work better than a slice because you can delete strings from it in constant time. A slice would outperform others only for small sizes, for all practical cases, deletion would require copying part of the slice.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.