Github user dbtsai commented on a diff in the pull request:

    https://github.com/apache/spark/pull/3462#discussion_r20961188
  
    --- Diff: mllib/src/main/scala/org/apache/spark/mllib/linalg/Vectors.scala 
---
    @@ -261,6 +261,57 @@ object Vectors {
             sys.error("Unsupported Breeze vector type: " + v.getClass.getName)
         }
       }
    +
    +  /**
    +   * Returns the p-norm of this vector.
    +   * @param vector input vector.
    +   * @param p norm.
    +   * @return norm in L^p^ space.
    +   */
    +  private[spark] def norm(vector: Vector, p: Double): Double = {
    +    require(p >= 1.0)
    +    val values = vector match {
    +      case dv: DenseVector => dv.values
    +      case sv: SparseVector => sv.values
    +      case v => throw new IllegalArgumentException("Do not support vector 
type " + v.getClass)
    +    }
    +    val size = values.size
    +
    +    if (p == 1) {
    +      var sum = 0.0
    +      var i = 0
    +      while (i < size) {
    +        sum += math.abs(values(i))
    +        i += 1
    +      }
    +      sum
    +    } else if (p == 2) {
    +      var sum = 0.0
    +      var i = 0
    +      while (i < size) {
    +        sum += values(i) * values(i)
    --- End diff --
    
    They will generate different bytecode, but I don't see the performance 
difference. Maybe `DSTORE` to store the `value` to local variable is more 
expensive than looping up twice. Or maybe JVM just optimizes it internally. I 
don't have preference.
    
    ```scala
    sum += values(i) * values(i)
    ```
    will translate to
    ```
       L24
        LINENUMBER 292 L24
        DLOAD 13
        ALOAD 4
        ILOAD 15
        DALOAD
        ALOAD 4
        ILOAD 15
        DALOAD
        DMUL
        DADD
        DSTORE 13
    ```
    while
    ```scala
    val value = values(i)
    sum += value * value
    ```
    will translate to
    ```
       L24
        LINENUMBER 292 L24
        ALOAD 4
        ILOAD 15
        DALOAD
        DSTORE 16
       L25
        LINENUMBER 293 L25
        DLOAD 13
        DLOAD 16
        DLOAD 16
        DMUL
        DADD
        DSTORE 13
    ```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to