Skip to content

Why are the branches of the if statement not implemented consistently? #1520

Description

@pjljvandelaar

Dear JSONCPP developers,

I was looking at the following if statement starting on

if (isArrayMultiLine) {

It took me some time to realize that the rather complex code in the then branch:

unsigned index = 0;
for (;;) {
const Value& childValue = value[index];
writeCommentBeforeValue(childValue);
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
if (!indented_)
writeIndent();
indented_ = true;
writeValue(childValue);
indented_ = false;
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*document_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}

is equal to joining the elements in the range [0,size) where size != 0 with a separator,
and a functional equivalent, yet simpler, implementation is

      for (unsigned index = 0; index < size ; ++index) {
        const Value& childValue = value[index];
        writeCommentBeforeValue(childValue);
        if (hasChildValue)
          writeWithIndent(childValues_[index]);
        else {
          if (!indented_)
            writeIndent();
          indented_ = true;
          writeValue(childValue);
          indented_ = false;
        }
        if (index < size -1) {
           *document_ << ",";
        }
        writeCommentAfterValueOnSameLine(childValue);
      }

I assume performance (saving a comparison) is the reason for the extra complexity.

Yet, when looking at the else branch

for (unsigned index = 0; index < size; ++index) {
if (index > 0)
*document_ << ", ";
*document_ << childValues_[index];
}

that is not optimized, like the then branch, to

      unsigned index = 0;
      for (;;) {
        *document_ << childValues_[index];
        if (++index == size)
		break;
        *document_ << ", ";
      }

So I wonder

  1. what is more important for jsoncpp code: readability or performance?
  2. Shouldn't these two branches not be implemented consistently?

Thanks in advance for your answers (and possibly code improvements)!

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions