Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memory allocations using range-based for loops #214

Closed
habemus-papadum opened this issue Feb 27, 2016 · 2 comments
Closed

Memory allocations using range-based for loops #214

habemus-papadum opened this issue Feb 27, 2016 · 2 comments

Comments

@habemus-papadum
Copy link

In the Readme, the following example is provided:

for (auto element : j) {
  std::cout << element << '\n';
}

Does this end up creating a copy of each array element during each iteration?

Are

for (const auto &element : j) {
  std::cout << element << '\n';
}

and

for (auto &element : j) {
  element["a"]=...;
}

better alternatives or is the version in the readme the optimal usage for all scenarios?

(In some sense this is just a basic c++ question. I don't really know how ranged for loop work in c++, or how to actually check what is happening in each of the scenarios, but in any case I am specifically curious about it works for basic_json's implementation)

Thanks!

@gregmarr
Copy link
Contributor

Yes, that first version will copy the elements. The second version is better. The third version is the required form if you want to change the elements of the j object itself.

habemus-papadum added a commit to habemus-papadum/json that referenced this issue Feb 29, 2016
Given that the the library aims to implement a highly performant json class, update the example so that beginners who perform benchmarks are more likely to use the library efficiently.  cf. nlohmann#214

cheers
@habemus-papadum
Copy link
Author

Thanks -- not that it really adds much to the effort, but I submitted a PR that tweaks the readme.

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

No branches or pull requests

3 participants