http://llvm.org/bugs/show_bug.cgi?id=20190

            Bug ID: 20190
           Summary: Feature Request: Spot redundant lambda and
                    std::function<> construction/destruction in loops
           Product: clang
           Version: unspecified
          Hardware: PC
                OS: Windows NT
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: Static Analyzer
          Assignee: [email protected]
          Reporter: [email protected]
                CC: [email protected]
    Classification: Unclassified

An inefficient code pattern I keep seeing looks a bit like this:

std::vector<std::function<void(int)>> vs;
for(...)
{
  double &f;
  vs.push_back(std::bind([](int, double) {...}, _1, f));
}

This code needlessly constructs a lambda every loop iteration, plus a
std::function every loop iteration. A more efficient implementation might be
this:

std::vector<std::function<void(int)>> vs;
for(...)
{
  double &f;
  static auto c=[](int, double) {...};
  vs.push_back(std::bind(c, _1, f));
}

Which saves on a lambda construction. Or even better again:

std::vector<std::function<void(int)>> vs;
std::function<void(int, double)> c=[](int, double) {...};
for(...)
{
  double &f;
  vs.push_back(std::bind(c, _1, f));
}

Which also saves on a std::function construction.

This may seem asinine for the clang static analyser to warn about, but many
programmers don't seem to realise that declaring lambdas inside a loop equals a
construction/destruction round. I myself find myself doing it because it's easy
to forget you're in a loop, and then you kick yourself later when you see the
assembler copying memory around needlessly.

A clang static analyser warning here would be useful.

Niall

-- 
You are receiving this mail because:
You are on the CC list for the bug.
_______________________________________________
LLVMbugs mailing list
[email protected]
http://lists.cs.uiuc.edu/mailman/listinfo/llvmbugs

Reply via email to